Kahn's algorithm for Topological Sorting topological sorting algorithm

Topological sorting for Directed Acyclic Graph (DAG)有向无环图 is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a 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()

out:

Following is a Topological Sort of the given graph
[4, 5, 2, 0, 3, 1]

Published 128 original articles · won praise 90 · views 4894

Guess you like

Origin blog.csdn.net/weixin_45405128/article/details/102502070
Recommended