📜  用于拓扑排序的Python程序(1)

📅  最后修改于: 2023-12-03 15:27:11.117000             🧑  作者: Mango

用于拓扑排序的Python程序
简介

拓扑排序是一种常用的图算法,它可以对一个有向无环图(DAG)进行排序。在DAG中,如果有一条从结点A到结点B的有向边,那么在排序中A一定出现在B的前面。本文将介绍一个用Python实现的拓扑排序程序。

程序实现

程序实现采用Kahn算法,具体步骤如下:

  1. 将DAG中所有入度为0的结点放入队列。
  2. 取出队首结点,输出该结点,并将其所有邻接结点的入度减1。
  3. 如果邻接结点的入度减为0,则将该结点加入队列。
  4. 重复上述步骤,直到队列为空。
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算法,使用起来简单方便,可以广泛应用于实际开发中。拓扑排序是图算法中重要的一环,仅限于有向无环图。