# 图遍历

图遍历是一种系统访问图中顶点的算法技术，通常通过深度优先搜索（DFS）或广度优先搜索（BFS）实现，用于求解最短路径、环检测、可达性、[拓扑排序](https://www.edgepedia.org/zh/topological-sorting)和垃圾回收等问题。<sup>[1](https://www.cs.cornell.edu/courses/cs2112/2017fa/lectures/lec_traversals/)</sup> 每种遍历算法都由相同的三部分组成：一个存放已发现但尚未处理的顶点的待办事项、一个存放已访问且不得重复访问的顶点的已访问集合，以及一个可选的正在构建的结果，如父节点、距离或访问顺序。<sup>[2](https://chalmersgu-data-structure-courses.github.io/dsabook/html/section-12.2.html)</sup> 待办事项的类型——栈或队列——正是区分不同策略的关键。

| 关键事实 | 值 |
|---|---|
| 邻接表下的时间 | DFS 和 BFS 均运行于 \( O(|V| + |E|) \)<sup>[3](https://stanford-cs161.github.io/winter2024/assets/files/lecture9-notes.pdf)</sup> |
| 邻接矩阵代价 | \( \Theta(n^{2}) \) 空间，常数时间边查询；DFS 代价为 \( O(v^{2}) \)<sup>[3](https://stanford-cs161.github.io/winter2024/assets/files/lecture9-notes.pdf)</sup><sup> • </sup><sup>[4](https://www.cs.cmu.edu/~15122/handouts/lectures/22-dfs.pdf)</sup> |
| BFS 保证 | 在无权图中计算最短路径距离和最短路径树<sup>[5](https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/196a95604877d326c6586e60477b59d4_MIT6_006S20_lec9.pdf)</sup> |
| DFS 保证 | 发现时间和完成时间支持环检测、拓扑排序和连通分量算法<sup>[1](https://www.cs.cornell.edu/courses/cs2112/2017fa/lectures/lec_traversals/)</sup> |
| 空间权衡 | DFS 树搜索使用 \( O(b \cdot d) \) 内存，若惰性生成后继则为 \( O(d) \)，而 BFS 在深度 \( d \)、分支因子 \( b \) 时为 \( O(b^{d}) \)<sup>[6](https://arxiv.org/pdf/1509.02709v2.pdf)</sup> |
| 前沿规模 | GPU 分布式 BFS 在 Frontier 超级计算机上已达到 160.845 TeraTEPS<sup>[7](https://dl.acm.org/doi/10.1145/3797905.3800549)</sup> |

## 工作原理

抽象地说，遍历可以表示为三色算法，其中节点为白色（未发现）、灰色（已发现，位于前沿）或黑色（已完成）；灰色节点构成白色区域与黑色区域之间的前沿，算法反复选取一个灰色节点并处理其边。<sup>[1](https://www.cs.cornell.edu/courses/cs2112/2017fa/lectures/lec_traversals/)</sup> 两种经典遍历之间唯一的区别在于存放前沿的数据结构：BFS 使用先进先出队列，DFS 使用后进先出栈。<sup>[3](https://stanford-cs161.github.io/winter2024/assets/files/lecture9-notes.pdf)</sup>

使用队列时，探索按层传播：BFS 在发现任何距离为 \( k+1 \) 的节点之前，先发现所有距离源点为 \( k \) 的节点，这就是它在无权图中能正确计算最短路径距离的原因。<sup>[8](https://tildesites.bowdoin.edu/~ltoma/teaching/cs231/2021spring/Lectures/L11-bfsdfs.pdf)</sup><sup> • </sup><sup>[3](https://stanford-cs161.github.io/winter2024/assets/files/lecture9-notes.pdf)</sup> 使用栈时，搜索沿一条路径尽可能深入，然后回溯。<sup>[1](https://www.cs.cornell.edu/courses/cs2112/2017fa/lectures/lec_traversals/)</sup> BFS 的线性性来自同样的核算：每个顶点恰好入队一次，共产生 \( 2|R| \) 次队列操作，其中 \( R \) 是从源点可达的顶点集合；每条边在有向图中被检查一次，在无向图中被检查两次。<sup>[9](https://people.eecs.berkeley.edu/~vazirani/algorithms/chap4.pdf)</sup>

## 具体做法

**从源点 s 开始的广度优先搜索。** 将所有顶点置为白色，然后将 \( s \) 置为灰色，令 \( d[s] = 0 \) 且无父节点，并将其入队；处理完一个顶点的邻居后，将其标记为黑色。反复出队一个顶点 \( u \)；对于每个白色邻居 \( v \)，将其染为灰色，令 \( d[v] = d[u] + 1 \)，记录 \( parent[v] = u \)，并将其入队。指向白色邻居的边发现一条树边；指向非白色邻居的边不会发现新顶点，不过在无向表示中，它可能是已记录的某条树边的反向关联。父指针构成一棵大小为 \( O(|V|) \) 的最短路径树，包含从每个可达顶点返回 \( s \) 的反向最短路径。<sup>[8](https://tildesites.bowdoin.edu/~ltoma/teaching/cs231/2021spring/Lectures/L11-bfsdfs.pdf)</sup><sup> • </sup><sup>[5](https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/196a95604877d326c6586e60477b59d4_MIT6_006S20_lec9.pdf)</sup> 在一个连通分量上，代价为 \( O(|V_{c}| + |E_{c}|) \)；在整个图上，为 \( O(|V| + |E|) \)。<sup>[8](https://tildesites.bowdoin.edu/~ltoma/teaching/cs231/2021spring/Lectures/L11-bfsdfs.pdf)</sup>

**深度优先搜索。** 递归地，每当发现一条通向新顶点的边，搜索就从新顶点继续。记录顶点首次被访问时的开始时间 \( d[u] \) 和其所有相邻顶点均被访问完毕时的完成时间 \( f[u] \)；在 DFS 树中，\( u \) 是 \( v \) 的后代，当且仅当 \( d[v] < d[u] < f[u] < f[v] \)。<sup>[8](https://tildesites.bowdoin.edu/~ltoma/teaching/cs231/2021spring/Lectures/L11-bfsdfs.pdf)</sup> 在有向图中，指向白色顶点的边分类为树边，指向灰色顶点的边分类为回边，而指向黑色顶点的边则利用发现时间和完成时间区分为前向边或交叉边。<sup>[10](https://gcallah.github.io/algorithms/GraphAlgorithms.html)</sup> 有向图包含环当且仅当存在回边，因此环可在线性时间内检测；等价地，指向灰色（当前正在访问）顶点的边即表示存在环。<sup>[1](https://www.cs.cornell.edu/courses/cs2112/2017fa/lectures/lec_traversals/)</sup><sup> • </sup><sup>[11](https://opendatastructures.org/ods-python/12_3_Graph_Traversal.html)</sup> DFS 也可以写成迭代形式，使用与 BFS 相同的结构，只是用栈代替队列。<sup>[8](https://tildesites.bowdoin.edu/~ltoma/teaching/cs231/2021spring/Lectures/L11-bfsdfs.pdf)</sup>

## 起源

BFS 和 DFS 在计算机时代之前就已知晓；DFS 作为高效图算法基础的能力，是在 Robert Tarjan 于《深度优先搜索与线性图算法》（SIAM Journal on Computing，1972 年）中为许多基本图问题——特别是双连通分量和强连通分量——提供了线性时间算法时确立的。<sup>[12](https://people.mpi-inf.mpg.de/~mehlhorn/ftp/NewToolbox/gtraverse.pdf)</sup><sup> • </sup><sup>[13](https://doi.org/10.1137/0201010)</sup> 这一传统还贯穿于另外两篇论文。Hopcroft 和 Tarjan 1971 年的斯坦福报告《图操作的高效算法》指出，深度优先搜索是该文所呈现的所有算法的基础。<sup>[14](http://i.stanford.edu/pub/cstr/reports/cs/tr/71/207/CS-TR-71-207.pdf)</sup> [Richard E. Korf](https://www.edgepedia.org/zh/richard-e-korf) 1985 年的论文提出了深度优先迭代加深和 IDA*。在 BFS 方面，一种最短路由算法在哈佛大学召开的国际交换理论研讨会上被提出。<sup>[15](https://ftp.gwdg.de/pub/misc/EMIS/journals/DMJDMV/vol-ismp/32_schrijver-alexander-sp.pdf)</sup> Deepak Ajwani、Roman Dementiev 和 Ulrich Meyer 于 2006 年发表了外存 BFS 算法的[计算](https://www.edgepedia.org/zh/computing)研究。<sup>[16](https://doi.org/10.5555/1109557.1109623)</sup>

## 变体

替换队列会改变保证性质。[Dijkstra 算法](https://www.edgepedia.org/zh/dijkstras-algorithm)反复取出暂定距离最小的顶点并松弛其出边，要求边权非负；使用二叉堆时运行时间为 \( O((|V| + |E|) \log |V|) \)。Bellman-Ford 算法对所有边更新 \( |V| - 1 \) 次，得到 \( O(|V| \cdot |E|) \) 的过程，且能处理负边权。<sup>[9](https://people.eecs.berkeley.edu/~vazirani/algorithms/chap4.pdf)</sup>

**迭代加深** 运行重复的深度有界 DFS，深度限制逐次递增。深度优先迭代加深（DFID）保证找到最短长度的解，同时仅使用 \( O(d) \) 空间，代价是在到达目标深度之前浪费计算；IDA* 在总代价 \( g + h \) 超过每次迭代递增的阈值时剪断分支，在指数树搜索中展开的节点数渐近地与 A* 相同。<sup>[17](https://www.cse.sc.edu/~mgv/csce580f09/gradPres/korf_IDAStar_1985.pdf)</sup>

**并行遍历** 利用了一个事实：给定 BFS 距离上的所有顶点可以并行访问。计算最短路径树的层同步并行 BFS 总工作量为 \( O(n + m) \)，跨度为 \( O(d \log n) \)，其中 \( d \) 为直径；当 \( d \in \Omega(n) \) 时 BFS 实际上是串行的，而低直径的真实世界图则能提供良好的并行性。<sup>[18](https://www.cs.cmu.edu/afs/cs/academic/class/15210-f25/www/algobook/graph-search/bfs.pdf)</sup> 在 GPU 上，iBFS 运行并发 BFS 遍历，可推广到单源、多源和全对最短路径，<sup>[19](https://asherliu.github.io/docs/sigmod16.pdf)</sup> 而 DiggerBees 将层次化块级工作窃取与两级栈应用于并行 DFS。<sup>[20](https://www.ssslab.cn/assets/papers/2026-niu-DiggerBees.pdf)</sup>

## 应用

遍历产生具体的产物，而不仅仅是访问。BFS 产生距离 \( \delta(s,v) \) 和构成最短路径树的父节点集合，并按距源点的距离将图分解为至多 \( n \) 个层次。<sup>[5](https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/196a95604877d326c6586e60477b59d4_MIT6_006S20_lec9.pdf)</sup><sup> • </sup><sup>[21](https://doi.org/10.1137/1.9781611972870.1)</sup> DFS 的发现时间和完成时间支持环检测、拓扑排序（仅适用于有向无环图，利用 DFS 完成时间插入列表前端）和强连通分量。<sup>[1](https://www.cs.cornell.edu/courses/cs2112/2017fa/lectures/lec_traversals/)</sup><sup> • </sup><sup>[10](https://gcallah.github.io/algorithms/GraphAlgorithms.html)</sup> BFS 层着色可在 \( O(n + m) \) 时间内检验二部性。<sup>[22](http://homepages.math.uic.edu/~jan/mcs401/traversals.pdf)</sup> 可达性计算是垃圾回收背后的机制，而遍历更广泛地服务于最佳路径搜索、路由和 DAG 检测。<sup>[1](https://www.cs.cornell.edu/courses/cs2112/2017fa/lectures/lec_traversals/)</sup> 在大规模场景下，BFS 是强连通分量检测、介数中心性和子图匹配的构建模块，并服务于[万维网](https://www.edgepedia.org/zh/world-wide-web)的爬取与分析、路径规划和状态空间探索。<sup>[7](https://dl.acm.org/doi/10.1145/3797905.3800549)</sup><sup> • </sup><sup>[21](https://doi.org/10.1137/1.9781611972870.1)</sup>

## 局限与替代方案

**表示方式。** 邻接矩阵占用 \( \Theta(n^{2}) \) 空间，但可在常数时间内检查 \( (i,j) \) 是否为边；[邻接表](https://www.edgepedia.org/zh/adjacency-list)占用 \( \Theta(m+n) \) 空间，枚举邻居需要 \( \deg(v) \) 时间。稀疏图（\( E \) 显著小于 \( V^{2} \)）优先使用邻接表；使用矩阵时，即使边很少，DFS 的代价也为 \( O(v^{2}) \)。<sup>[3](https://stanford-cs161.github.io/winter2024/assets/files/lecture9-notes.pdf)</sup><sup> • </sup><sup>[4](https://www.cs.cmu.edu/~15122/handouts/lectures/22-dfs.pdf)</sup><sup> • </sup><sup>[10](https://gcallah.github.io/algorithms/GraphAlgorithms.html)</sup>

**失效模式。** BFS 的空间需求是其最关键的缺点：在分支因子为 \( b \)、搜索深度为 \( d \) 时，最坏情况下需要存储 \( O(b^{d}) \) 个节点。<sup>[17](https://www.cse.sc.edu/~mgv/csce580f09/gradPres/korf_IDAStar_1985.pdf)</sup> 在具有无限路径的隐式图上，DFS 可能沿一条路径无尽地追求而永不回溯，这是 BFS 通过逐层搜索所避免的弱点；迭代加深结合了两者的优点。<sup>[4](https://www.cs.cmu.edu/~15122/handouts/lectures/22-dfs.pdf)</sup> 深度有界 DFS 图搜索在一般图中不是完备的搜索方法，因为它可能将自己与搜索空间的某些区域隔绝开来。<sup>[6](https://arxiv.org/pdf/1509.02709v2.pdf)</sup> 递归 DFS 在大图上还可能导致栈溢出，因此显式栈是更安全的实现方式。<sup>[11](https://opendatastructures.org/ods-python/12_3_Graph_Traversal.html)</sup> 当图超出主存时，将图放在磁盘上并使用先进先出队列在外存中执行 BFS，最坏情况下需要 \( \Theta(m) \) 次 I/O，即使有一半的图在内存中，其运行时间也偏离 RAM 预测——是数小时而非数分钟。<sup>[21](https://doi.org/10.1137/1.9781611972870.1)</sup>

**替代方案。** BFS 的代数表述是在带掩码的 OR-AND 半环下布尔前沿传播的递推，例如 \( f_{k+1} = (A \cdot f_{k}) \land \neg visited \)，其中 \( A \) 为 \( n \times n \) 的邻接矩阵，但对非零元素的冗余操作使其次优；最优代数 BFS 在稀疏图上需要 \( O(n) \) 次代数操作，而理论上最优的稀疏矩阵方法为 \( O(m) \)。<sup>[23](https://ar5iv.labs.arxiv.org/html/1906.03113)</sup> 对于无法放入内存的图，按源点排序的边上的外存 DFS 运行于 \( O((1 + V/M) \cdot \mathrm{scan}(E) + V) \) 次 I/O，支持连通分量、拓扑排序和可达性。<sup>[24](https://www.ittc.ku.edu/~jsv/Papers/CGG95.external_graph.pdf)</sup>

## References

1. [Graph traversals (Cornell CS 2112 lecture notes)](https://www.cs.cornell.edu/courses/cs2112/2017fa/lectures/lec_traversals/)
2. [DSABook – Traversing graphs: DFS and BFS](https://chalmersgu-data-structure-courses.github.io/dsabook/html/section-12.2.html)
3. [CS 161 (Stanford, Winter 2024) Lecture 9: Graph Traversal](https://stanford-cs161.github.io/winter2024/assets/files/lecture9-notes.pdf)
4. [Lecture 22: Search in Graphs (CMU 15-122)](https://www.cs.cmu.edu/~15122/handouts/lectures/22-dfs.pdf)
5. [MIT 6.006 Introduction to Algorithms, Lecture 9: Breadth-First Search (Spring 2020)](https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/196a95604877d326c6586e60477b59d4_MIT6_006S20_lec9.pdf)
6. [A Topological Approach to Meta-heuristics: Expected Runtime of BFS and DFS (arXiv)](https://arxiv.org/pdf/1509.02709v2.pdf)
7. [CORE-BFS: Communication-Optimized REctangular-partitioned BFS Achieving 160.845 TeraTEPS on Frontier Supercomputer](https://dl.acm.org/doi/10.1145/3797905.3800549)
8. [Graph Traversal: Breadth-First Search and Depth-First Search (Bowdoin CS 231 lecture)](https://tildesites.bowdoin.edu/~ltoma/teaching/cs231/2021spring/Lectures/L11-bfsdfs.pdf)
9. [Algorithms (Dasgupta, Papadimitriou, Vazirani), Chapter 4: Paths in graphs](https://people.eecs.berkeley.edu/~vazirani/algorithms/chap4.pdf)
10. [Design and Analysis of Algorithms: Graph Algorithms (NYU, Jonathan L. Gross course notes)](https://gcallah.github.io/algorithms/GraphAlgorithms.html)
11. [Open Data Structures (Python), Section 12.3: Graph Traversal (Pat Morin)](https://opendatastructures.org/ods-python/12_3_Graph_Traversal.html)
12. [Mehlhorn & Sanders, Algorithms and Data Structures: Graph Traversal (chapter)](https://people.mpi-inf.mpg.de/~mehlhorn/ftp/NewToolbox/gtraverse.pdf)
13. [Robert Tarjan (1972). Depth-First Search and Linear Graph Algorithms. SIAM Journal on Computing.](https://doi.org/10.1137/0201010)
14. [Tarjan, Efficient Algorithms for Graph Manipulation (Stanford CS-TR-71-207, 1971)](http://i.stanford.edu/pub/cstr/reports/cs/tr/71/207/CS-TR-71-207.pdf)
15. [Alexander Schrijver, history of combinatorial optimization (Documenta Mathematica, ISMP volume)](https://ftp.gwdg.de/pub/misc/EMIS/journals/DMJDMV/vol-ismp/32_schrijver-alexander-sp.pdf)
16. [Deepak Ajwani, Roman Dementiev, Ulrich Meyer (2006). A computational study of external-memory BFS algorithms. .](https://doi.org/10.5555/1109557.1109623)
17. [Depth-First Iterative-Deepening: An Optimal Admissible Tree Search (Korf, 1985)](https://www.cse.sc.edu/~mgv/csce580f09/gradPres/korf_IDAStar_1985.pdf)
18. [Parallel and Sequential Algorithms (CMU 15-210 algobook), Breadth-First Search chapter](https://www.cs.cmu.edu/afs/cs/academic/class/15210-f25/www/algobook/graph-search/bfs.pdf)
19. [iBFS: Concurrent Breadth-First Search on GPUs (SIGMOD 2016)](https://asherliu.github.io/docs/sigmod16.pdf)
20. [DiggerBees: Depth First Search Leveraging Hierarchical Block-Level Stealing on GPUs](https://www.ssslab.cn/assets/papers/2026-niu-DiggerBees.pdf)
21. [Improved external memory BFS implementations](https://doi.org/10.1137/1.9781611972870.1)
22. [Implementing Graph Traversals (UIC MCS 401, Jan Verschelde)](http://homepages.math.uic.edu/~jan/mcs401/traversals.pdf)
23. [Optimal algebraic Breadth-First Search for sparse graphs](https://ar5iv.labs.arxiv.org/html/1906.03113)
24. [Design and analysis of external graph algorithms (external DFS and closed semi-ring computation)](https://www.ittc.ku.edu/~jsv/Papers/CGG95.external_graph.pdf)

---
*Initially written Sep 29, 2026 · Edited: 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/graph-traversal

English original: https://www.edgepedia.org/graph-traversal
