📅  最后修改于: 2023-12-03 15:27:11.117000             🧑  作者: Mango
拓扑排序是一种常用的图算法,它可以对一个有向无环图(DAG)进行排序。在DAG中,如果有一条从结点A到结点B的有向边,那么在排序中A一定出现在B的前面。本文将介绍一个用Python实现的拓扑排序程序。
程序实现采用Kahn算法,具体步骤如下:
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 = [u for u in in_degree if in_degree[u] == 0]
result = []
while queue:
u = queue.pop(0)
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:
return None
首先,构建一个DAG:
graph = {
'A': ['B', 'C', 'D'],
'B': ['E'],
'C': ['D', 'F'],
'D': ['E', 'F'],
'E': [],
'F': []
}
然后调用拓扑排序函数:
result = topological_sort(graph)
if result:
print(' -> '.join(result))
else:
print('The graph contains a cycle.')
输出结果为:
A -> C -> D -> B -> F -> E
本文介绍了一个用Python实现的拓扑排序程序,采用了Kahn算法,使用起来简单方便,可以广泛应用于实际开发中。拓扑排序是图算法中重要的一环,仅限于有向无环图。