1

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?

eyllanesc
  • 190,383
  • 15
  • 87
  • 142
Johnny
  • 13
  • 2
  • What have you tried so far? Please post a [mcve](https://stackoverflow.com/help/mcve) so that we can help you further – G. Anderson Oct 19 '18 at 17:03
  • How about you try solving it in [NetworkX](https://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.dag.topological_sort.html) and come back with another question if you get stuck? – Nils Werner Oct 19 '18 at 17:44
  • Thank you Nils, I tried NetworkX and did the following: `import numpy as np import networkx as nx a = np.array([[1,1,0,0],[0,1,0,0],[1,0,1,1],[0,1,0,1]]) g = nx.from_numpy_matrix(a) nx.topological_sort(g)` How can I get the output as a vector containing the topological order then? Sorry for being a bit quick-tempered last night. – Johnny Oct 20 '18 at 09:28

1 Answers1

0

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.

Some
  • 368
  • 1
  • 9