Kahn’s algorithm for Topological Sorting 拓扑排序算法

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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值