从邻接矩阵获取图的拓扑顺序

时间:2018-10-19 17:02:18

标签: python adjacency-matrix python-3.7 topological-sort

对于给定的邻接矩阵,我想获得图的拓扑顺序,作为Python的输出。 例如这样的东西:

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]])

您有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我认为关于拓扑排序的信息http://py-algorithm.blogspot.com/2011/09/blog-post.html足够。

例如矩阵排序有这样的实现:

 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#осталось выбрать в обратном порядке

它是俄语,所以您可以翻译它,但是我认为算法应该足够清楚。