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]

### Topological 排序概念 Topological 排序是一种针对有向无环图(DAG)的操作,其目的是将图中的顶点按某种线性顺序排列,从而满足对于每条有向边(u, v),顶点u在线性序列中都位于v之前[^1]。 ### 实现方法 #### Kahn's Algorithm(基于入度) Kahn算法通过不断移除入度为0的节点来构建拓扑排序。具体过程如下: 1. 记录所有节点的入度; 2. 将所有入度为零的节点加入队列; 3. 取出队首元素并记录该节点作为当前部分的结果之一; 4. 对于由取出节点指向的所有其他节点减少它们各自的入度计数; 5. 如果某个被减去入度后的节点此时入度变为0,则将其加入队列; 6. 重复上述操作直到没有新的节点可以加入队列为止。 如果最终得到的结果集长度等于原图中节点数量说明成功完成了一次完整的拓扑排序;反之则表示存在至少一个环路无法形成合法的拓扑序列[^2]。 Python代码实现: ```python from collections import deque,defaultdict def topological_sort_kahn(graph): indegree = defaultdict(int) # Calculate the in-degrees of all vertices. for node in graph: for neighbor in graph[node]: indegree[neighbor] += 1 queue = deque([node for node in graph if indegree[node]==0]) result = [] while queue: current_node = queue.popleft() result.append(current_node) for neighbor in graph[current_node]: indegree[neighbor]-=1 if indegree[neighbor]==0: queue.append(neighbor) return result if len(result)==len(graph) else None ``` 另一种常见的实现方式是利用深度优先搜索DFS来进行逆后序遍历,这里不再赘述。 ### 应用场景 - **项目管理**:在一个复杂的工程项目里可能存在多个子任务之间相互依赖的情况,这时就可以借助topological sorting 来规划合理的执行路径。 - **编译器设计**:当涉及到模块间的依赖关系解析时,也可以采用此技术确保各个组件能够按照正确的加载顺序被执行。 - **课程安排**:大学选课系统经常会遇到先修课的要求,即某些高级课程需要学生已经完成了特定的基础课程学习之后才能注册,在这种情况下同样适用topological sorting 进行合理的时间表制定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值