토폴로지 정렬 위상 정렬 알고리즘에 대한 칸의 알고리즘

위한 위상 정렬  D는 irected  환상  G의 라프 (DAG)를有向无环图 IS 정점의 선형 정렬되도록 유 순서에 V 앞에 오는 모든 방향 에지 UV 대 정점. 그래프는 DAG 아닌 경우 그래프 위상 정렬은 불가능하다.

from collections import defaultdict
class Graph:
    def __init__(self,vertices):
        self.graph = defaultdict(list)
        self.V=vertices

    def addEdge(self,u,v):
        self.graph[u].append(v)

    #the function to do Topological Sort
    def topologicalSort(self):
        #create a vector to store indegrees of all vertices
        in_degree=[0]*(self.V)
        for i in self.graph:
            for j in self.graph[i]:
                in_degree[j]+=1
        # Create an queue and enqueue all vertices with indegree 0
        queue=[]
        for i in range(self.V):
            if in_degree[i]==0:
                queue.append(i)
        #Initialize count of visited vertices
        cnt=0
        # Create a vector to store result (A topological ordering of the vertices)
        top_order=[]
        # One by one dequeue vertices from queue and enqueue adjacents if indegree of adjacent becomes 0
        while queue:
            u=queue.pop(0)
            top_order.append(u)

            for i in self.graph[u]:
                in_degree[i]-=1
                if in_degree[i]==0:
                    queue.append(i)
            cnt+=1
        if cnt!=self.V:
            print("there exists a cycle in the graph")
        else:
            print(top_order)


g=Graph(6)
g.addEdge(5, 2)
g.addEdge(5, 0)
g.addEdge(4, 0)
g.addEdge(4, 1)
g.addEdge(2, 3)
g.addEdge(3, 1)
print("Following is a Topological Sort of the given graph")
g.topologicalSort()

밖:

주어진 그래프의 토폴로지에 따라 정렬된다
[4, 5, 2, 0, 3, 1]

게시 된 128 개 원래 기사 · 원 찬양 90 · 전망 4894

추천

출처blog.csdn.net/weixin_45405128/article/details/102502070