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

问题描述 投票:0回答:1

对于给定的邻接矩阵,我想将图的拓扑顺序作为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]])

你有什么建议?

python adjacency-matrix python-3.7 topological-sort
1个回答
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#осталось выбрать в обратном порядке

它是俄语,所以你可以转换它,但我认为算法应该足够清楚。

© www.soinside.com 2019 - 2024. All rights reserved.