Search code examples
pythonadjacency-matrixpython-3.7topological-sort

Get topological order of graph from adjacency matrix


For a given adjacency matrix I would like to get the topological order of the graph as output in Python. For example something like this:

In[1]: a = np.array([[1,1,0,0],[0,1,0,0],[1,0,1,1],[0,1,0,1]])
In[1]: topoOrder(a)
Out[1]: array([[3, 1, 4, 2]])

Do you have any recommendations?


Solution

  • I think there is http://py-algorithm.blogspot.com/2011/09/blog-post.html enough information about topological sorting.

    For example for matrix sorting there is such realization:

     class Graph:
        def __init__(self):
            self.nodes=[[0,0,0,0,0,0],
                        [1,0,0,1,0,0],
                        [0,1,0,1,0,0],
                        [0,0,0,0,0,0],
                        [0,0,0,1,0,0]
                        ];
            self.count=range(len(self.nodes))
    
        def GetInputNodesArray(self):
            array = []
            for i in self.count: 
                step=0
                for j in self.count:
                    if self.nodes[i][j]==1:step+=1
                array.insert(i,step)
            return array;
    
        def TopologicSort(self):
            levels =[];
            workArray = self.GetInputNodesArray();
            completedCounter = 0;
            currentLevel = 0;
            while (completedCounter != len(self.nodes)):
                for i in self.count:
                    if (workArray[i] == 0):
                        ind=0
                        #добавляем обработанную вершину
                        levels.insert(completedCounter,i);
                        for node in self.nodes:
                            if node[i]==1:
                                workArray[ind]-=1
                            ind+=1
    
                        workArray[i] = -1; # Помечаем вершину как обработанную
                        completedCounter+=1;
                currentLevel+=1;
            levels.reverse()
            return levels#осталось выбрать в обратном порядке
    

    It is on russian, so your can tranlate it, but I think algorithms should be clear enough.