放坡偏序(Topological Sorting)是一种对有向无环图(Directed Acyclic Graph, DAG)的顶点进行排序的算法,使得对于每一条有向边 (u, v),顶点 u 都在顶点 v 之前。拓扑排序在诸如任务调度、课程安排、软件依赖关系管理等领域有广泛应用。
拓扑排序主要有两种类型:
from collections import defaultdict, deque
def topological_sort(graph):
in_degree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
in_degree[v] += 1
queue = deque([u for u in graph if in_degree[u] == 0])
result = []
while queue:
u = queue.popleft()
result.append(u)
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)
if len(result) == len(graph):
return result
else:
raise ValueError("Graph has at least one cycle, topological sort not possible")
# 示例图
graph = {
'A': ['C'],
'B': ['C', 'D'],
'C': ['E'],
'D': ['F'],
'E': ['F'],
'F': []
}
print(topological_sort(graph)) # 输出: ['A', 'B', 'C', 'E', 'D', 'F']
通过以上方法,可以有效解决拓扑排序过程中遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云