# 拓扑排序

**拓扑排序**（Topological sorting）是将有向图的顶点排成一个线性顺序，使得对于每一条从顶点 u 指向顶点 v 的有向边，u 都排在 v 之前。这样的顺序存在，当且仅当该图是有向无环图（DAG），即不含任何有向环的有向图；一旦存在环，就不可能给出线性顺序，因为环上的每个顶点都必须排在其余顶点之前。<sup>[1](https://networkx.org/nx-guides/content/algorithms/dag/index.html)</sup><sup> • </sup><sup>[2](https://algs4.cs.princeton.edu/42digraph/)</sup> 这种顺序一般并不唯一：任何与所有边的方向都相容的排列都是合法的拓扑排序。<sup>[3](https://networkx.org/documentation/networkx-1.8/reference/generated/networkx.algorithms.dag.topological_sort.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 定义 | 将有向图的所有顶点排成一个线性顺序，使每条边 (u, v) 都把 u 排在 v 之前<sup>[1](https://networkx.org/nx-guides/content/algorithms/dag/index.html)</sup> |
| 存在性 | 有向图存在拓扑顺序，当且仅当它是有向无环图<sup>[2](https://algs4.cs.princeton.edu/42digraph/)</sup> |
| 唯一性 | 拓扑顺序唯一，当且仅当图中顺序里每一对相邻顶点之间都有一条有向边，即存在一条哈密顿路径<sup>[2](https://algs4.cs.princeton.edu/42digraph/)</sup> |
| 运行时间 | 卡恩算法与深度优先搜索法的时间都与 V + E 成正比，额外空间为 O(V)<sup>[2](https://algs4.cs.princeton.edu/42digraph/)</sup><sup> • </sup><sup>[4](https://algs4.cs.princeton.edu/cheatsheet/)</sup> |
| 起源 | 基于队列的方法由亚瑟·卡恩于 1962 年首次发表于《美国计算机学会通讯》<sup>[5](https://courses.grainger.illinois.edu/cs374/fa2022/a/lec/notes/06-dfs.pdf)</sup><sup> • </sup><sup>[6](https://doi.org/10.1145/368996.369025)</sup> |
| 典型用途 | 依据依赖约束调度作业或任务；也用于指令调度、电子表格重算、makefile、链接器以及数据库表加载<sup>[1](https://networkx.org/nx-guides/content/algorithms/dag/index.html)</sup> |
| 库支持 | Python 的 `graphlib.TopologicalSorter`（3.9 版）以及 NetworkX 的 `topological_sort` 和 `topological_generations`<sup>[7](https://docs.python.org/3/library/graphlib.html)</sup><sup> • </sup><sup>[8](https://networkx.org/documentation/stable/reference/algorithms/dag.html)</sup> |

## 定义与存在性

对于有向无环图 G = (V, E)，拓扑排序把全部顶点排成一个序列，使得只要图中存在边 (u, v)，u 在该序列中就排在 v 之前。一个有用的直观图景是把顶点摆在一条水平线上，让每条有向边都从左指向右。<sup>[1](https://networkx.org/nx-guides/content/algorithms/dag/index.html)</sup>

与无环性的联系在两个方向上都是精确的。有向图存在拓扑顺序，当且仅当它是 DAG：任何环都会要求环上每个顶点都排在前一个顶点之前，这是不可能的；反过来，无环图总能给出一种顺序。<sup>[2](https://algs4.cs.princeton.edu/42digraph/)</sup> 正因如此，环检测被内建于每一种拓扑排序实现之中：如果算法结束时仍有顶点或边未被处理，图中就含有环。<sup>[1](https://networkx.org/nx-guides/content/algorithms/dag/index.html)</sup>

排序是节点的一种非唯一排列。当存在多种顺序时，只要交换一对没有边相连的相邻顶点，就能得到另一种顺序。有向图的拓扑顺序唯一，恰好当顺序中每一对相邻顶点之间都有有向边，这等价于说该 DAG 含有一条哈密顿路径。<sup>[2](https://algs4.cs.princeton.edu/42digraph/)</sup>

## 卡恩算法

亚瑟·卡恩于 1962 年首次发表的方法从顺序的前端入手。它先收集入度为零的节点集合 S——在任何非空无环图中，这样的节点至少存在一个——然后反复执行：从 S 中取出一个节点 N，追加到输出列表 L，并删除从 N 指向节点 M 的每条边；每当这样的删除使 M 不再有其他入边时，M 就加入 S。如果 S 为空时图中仍有边，则图至少含有一个环；否则 L 就是一个拓扑排序后的顺序。<sup>[1](https://networkx.org/nx-guides/content/algorithms/dag/index.html)</sup><sup> • </sup><sup>[5](https://courses.grainger.illinois.edu/cs374/fa2022/a/lec/notes/06-dfs.pdf)</sup>

实践中并不真的销毁边。实现会为每个顶点维护一个入度计数，并在前驱被输出时递减它，这样既保留了输入图，又保持了同样的线性时间行为。NetworkX 的 `topological_generations` 就是这样做的；同样的改动也能处理多重图，只需按平行边的条数而非按一递减入度。<sup>[1](https://networkx.org/nx-guides/content/algorithms/dag/index.html)</sup>

卡恩方法的一个自然副产品是把 DAG 分层为若干代：第 0 层是无依赖的节点，第 1 层是其依赖全部位于第 0 层的节点，依此类推。每一代中的节点，其祖先全部位于更早的代，其后代全部位于更晚的代，且每个节点都被放入它所能属于的最早一代。<sup>[9](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.dag.topological_generations.html)</sup> 一个节点的代等于从该节点到最远叶子的最大路径距离。<sup>[9](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.dag.topological_generations.html)</sup>

## 深度优先搜索法

另一种算法对整个图运行深度优先搜索，并按逆后序输出顶点，即搜索完成各顶点顺序的逆序。在 DAG 中，逆后序总是拓扑顺序，计算时间与 V + E 成正比。<sup>[2](https://algs4.cs.princeton.edu/42digraph/)</sup> 普林斯顿《算法》中的实现先检查有向环，仅当不存在环时才生成顺序；它记录每个顶点在顺序中的秩，并在图本身之外使用 O(V) 的额外空间。<sup>[10](https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Topological.java.html)</sup><sup> • </sup><sup>[4](https://algs4.cs.princeton.edu/cheatsheet/)</sup> 一种非递归的、基于队列的变体 TopologicalX 直接维护入度数组，是卡恩算法思想的迭代表达。<sup>[10](https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Topological.java.html)</sup><sup> • </sup><sup>[2](https://algs4.cs.princeton.edu/42digraph/)</sup>

## 应用

最典型的应用是依据依赖关系调度一系列作业或任务：顶点表示作业，从 u 到 v 的边表示作业 u 必须在作业 v 开始前完成，拓扑排序给出一个合法的执行顺序。这种依赖图中的环就是循环依赖，无法一致地调度。<sup>[1](https://networkx.org/nx-guides/content/algorithms/dag/index.html)</sup>

一项密切相关的用途最早在 20 世纪 60 年代初的 PERT 项目管理技术中得到研究，其中顶点是项目里程碑，边是里程碑之间的任务；拓扑排序是寻找关键路径——控制整个工期长度的里程碑与任务序列——的线性时间算法的基础。<sup>[1](https://networkx.org/nx-guides/content/algorithms/dag/index.html)</sup> 在计算机科学中，同样的排序问题出现在指令调度、重算电子表格值时确定公式单元格的求值顺序、逻辑综合、确定 makefile 中编译任务的顺序、数据序列化、解析链接器中的符号依赖，以及决定带外键的数据库表的加载顺序等场合。<sup>[1](https://networkx.org/nx-guides/content/algorithms/dag/index.html)</sup> 其他列出的用途包括课程先修要求、类继承检查、死锁检测和电子表格公式求值。<sup>[2](https://algs4.cs.princeton.edu/42digraph/)</sup>

拓扑顺序还作为子程序服务于其他算法。DAG 中的最短路径与最长路径通过按拓扑顺序松弛边来计算；拓扑排序还能回答一个 DAG 是否存在有向[哈密顿路径](https://www.edgepedia.org/zh/hamiltonian-path)：检查顺序中每一对相邻顶点之间是否都有一条边。<sup>[2](https://algs4.cs.princeton.edu/42digraph/)</sup>

## 库实现

Python 标准库模块 `graphlib` 自 3.9 版起提供 `TopologicalSorter`。对于一次性排序，`static_order()` 返回一个按拓扑顺序遍历节点的迭代器；同一层内节点之间的顺序取决于插入顺序。对于并行执行，调用方先调用 `prepare()`，然后反复从 `get_ready()` 取出节点、处理它们，并用 `done()` 标记完成，从而解除其后继的阻塞。如果存在环，`prepare()` 会抛出 `CycleError`，它是 `ValueError` 的子类，其 `args` 包含构成该环的节点列表，首尾节点相同；即便如此，`get_ready()` 仍能返回在环阻塞进展之前尚可达的那些节点。<sup>[7](https://docs.python.org/3/library/graphlib.html)</sup>

NetworkX 提供 `topological_sort`，它返回一个按排序顺序生成节点的生成器，并在图不是 DAG 时抛出 `NetworkXUnfeasible`；此外还有 `topological_generations`、用于枚举所有合法顺序的 `all_topological_sorts`，以及用于按键函数确定唯一顺序的 `lexicographical_topological_sort`。这些函数一般不自带无环性验证；单独的 `is_directed_acyclic_graph` 检查留给用户自行调用。<sup>[8](https://networkx.org/documentation/stable/reference/algorithms/dag.html)</sup><sup> • </sup><sup>[3](https://networkx.org/documentation/networkx-1.8/reference/generated/networkx.algorithms.dag.topological_sort.html)</sup>

## 变体与扩展

若干改进针对的是单一静态排序之外的场景。增量算法在向一个 n 顶点无环图添加弧的过程中维护其拓扑顺序，并在产生环时检测出来；伯恩哈德·霍伊普勒、泰利凯帕利·卡维塔、罗杰斯·马修、悉达多·森和罗伯特·恩德雷·塔里扬提出的两种在线算法以 O(m<sup>3/2</sup>) 的总时间处理 m 条弧的添加，并可扩展为维护图的强连通分量。<sup>[11](https://arxiv.org/abs/1105.2397)</sup> 约束拓扑排序问的是：一个顶点带标签的 DAG 是否存在一种拓扑排序，使其拼出的词属于给定的正则语言；安托万·阿马里利与查尔斯·佩珀曼研究了这一问题，其复杂度取决于目标语言。<sup>[12](https://arxiv.org/abs/1707.04310)</sup>

## References

1. [Directed Acyclic Graphs & Topological Sort, NetworkX Notebooks](https://networkx.org/nx-guides/content/algorithms/dag/index.html)
2. [Directed Graphs, Section 4.2, Algorithms, 4th Edition (Sedgewick & Wayne), Princeton algs4](https://algs4.cs.princeton.edu/42digraph/)
3. [topological_sort, NetworkX 1.8 documentation](https://networkx.org/documentation/networkx-1.8/reference/generated/networkx.algorithms.dag.topological_sort.html)
4. [Algorithms and Data Structures Cheatsheet, Princeton algs4](https://algs4.cs.princeton.edu/cheatsheet/)
5. [6.5. Topological Sort, CS 374 lecture notes, University of Illinois](https://courses.grainger.illinois.edu/cs374/fa2022/a/lec/notes/06-dfs.pdf)
6. [A. B. Kahn, Topological sorting of large networks, Communications of the ACM (1962)](https://doi.org/10.1145/368996.369025)
7. [graphlib, Functionality to operate with graph-like structures, Python documentation](https://docs.python.org/3/library/graphlib.html)
8. [Directed Acyclic Graphs, NetworkX 3.7 documentation](https://networkx.org/documentation/stable/reference/algorithms/dag.html)
9. [topological_generations, NetworkX 3.7 documentation](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.dag.topological_generations.html)
10. [Topological.java, Princeton algs4 code](https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Topological.java.html)
11. [B. Haeupler, T. Kavitha, R. Mathew, S. Sen, R. E. Tarjan, Incremental Cycle Detection, Topological Ordering, and Strong Component Maintenance, arXiv](https://arxiv.org/abs/1105.2397)
12. [A. Amarilli, C. Paperman, Topological Sorting under Regular Constraints, arXiv](https://arxiv.org/abs/1707.04310)

---
*Initially written Sep 17, 2026 · Reviewed: Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Algorithms and computational methods › Graph and network algorithms › Graph traversal and search

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/topological-sorting

English original: https://www.edgepedia.org/topological-sorting
