# 弗洛伊德–沃舍尔算法

**弗洛伊德–沃舍尔算法**（Floyd–Warshall algorithm）是一种动态规划算法，用于求解加权有向图中的全源最短路径问题：它在 Θ(V³) 时间内求出每一对顶点之间最短路径的长度。只要图中不含负权环，边的权重可以为负。<sup>[1](https://xlinux.nist.gov/dads/HTML/floydWarshall.html)</sup> 它最适合稠密图，同时也能检测负权环。<sup>[2](https://networkx.org/documentation/networkx-0.99/reference/generated/networkx.floyd_warshall.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 解决的问题 | 加权有向图中的全源最短路径（APSP）；允许负边权，不允许负权环<sup>[1](https://xlinux.nist.gov/dads/HTML/floydWarshall.html)</sup> |
| 时间复杂度 | Θ(V³)，来自 O(V³) 个子问题，每个子问题可在 O(1) 时间内求解<sup>[3](https://ocw.mit.edu/courses/6-046j-design-and-analysis-of-algorithms-spring-2015/312f4a419009b58f8147b75975db4347_MIT6_046JS15_lec11.pdf)</sup> |
| 空间 | O(n²)；只需一个二维数组，因为每一轮都会覆盖上一轮的值<sup>[4](https://www.usna.edu/Users/cs/wcbrown/courses/S17SI335/notes/05/notes.html)</sup> |
| 递推式 | \( d^{(k)}_{ij} = \min\left(d^{(k-1)}_{ij},\ d^{(k-1)}_{ik} + d^{(k-1)}_{kj}\right) \)，其中 \( d^{(0)}_{ij} = w_{ij} \)<sup>[5](https://www.cs.umd.edu/~meesh/cmsc351/mount/lectures/lect24-floyd-warshall.pdf)</sup> |
| 负权环检测 | 当且仅当最终存在某个顶点 \( u \) 使 \( d(u,u) < 0 \) 时，图中存在负权环<sup>[6](https://web.stanford.edu/class/archive/cs/cs161/cs161.1178/notes/bf-fw.pdf)</sup> |
| 原始文献 | 斯蒂芬·沃舍尔，*Journal of the ACM* 9(1):11–12（1962）；罗伯特·W·弗洛伊德，*Communications of the ACM* 5(6):345（1962）<sup>[7](https://sigmod.org/publications/dblp/db/journals/jacm/Warshall62.html)</sup><sup> • </sup><sup>[8](https://cir.nii.ac.jp/crid/1362825893844317696)</sup> |
| 最佳适用场景 | 稠密图，或含负权、使迪杰斯特拉算法失效的图<sup>[9](https://networkx.org/documentation/latest/_modules/networkx/algorithms/shortest_paths/dense.html)</sup> |

## 算法

该算法维护一个 \( n \times n \) 的距离矩阵，初始化为图的邻接矩阵：每条边填入边权 \( w(u,v) \)，对角线上填 0，不存在的边填无穷大。<sup>[4](https://www.usna.edu/Users/cs/wcbrown/courses/S17SI335/notes/05/notes.html)</sup> 随后执行 \( n \) 轮。在第 \( k \) 轮中，顶点 \( k \) 被接纳为可能的中间点，每一对 \((u, v)\) 都通过松弛进行更新

\[ d_{uv} \leftarrow \min\left(d_{uv},\ d_{uk} + d_{kv}\right). \]

经过 \( n \) 轮后，\( d_{uv} \) 即为从 \( u \) 到 \( v \) 的最短路径距离。<sup>[3](https://ocw.mit.edu/courses/6-046j-design-and-analysis-of-algorithms-spring-2015/312f4a419009b58f8147b75975db4347_MIT6_046JS15_lec11.pdf)</sup> 整个计算是分别以 \( k \)、\( u \)、\( v \) 为循环变量的三层嵌套循环，循环体只有一次比较和一次可能的赋值。<sup>[4](https://www.usna.edu/Users/cs/wcbrown/courses/S17SI335/notes/05/notes.html)</sup>

**为什么正确。** 定义 \( d^{(k)}_{uv} \) 为从 \( u \) 到 \( v \)、且中间顶点全部落在 \(\{1, 2, \ldots, k\}\) 中的最短路径的权重。使用这一顶点集合的最短路径要么经过 \( k \)，要么不经过。若不经过，其权重为 \( d^{(k-1)}_{uv} \)。若经过，则（假设无负权环，因而最短路径是简单路径）它恰好经过 \( k \) 一次，其前后两段内部只使用编号不超过 \( k-1 \) 的顶点，权重为 \( d^{(k-1)}_{uk} + d^{(k-1)}_{kv} \)。对两种情形取最小值即得递推式。<sup>[5](https://www.cs.umd.edu/~meesh/cmsc351/mount/lectures/lect24-floyd-warshall.pdf)</sup><sup> • </sup><sup>[6](https://web.stanford.edu/class/archive/cs/cs161/cs161.1178/notes/bf-fw.pdf)</sup>

**空间。** 动态规划表看似需要 \( u \)、\( v \)、\( k \) 三个下标，共 O(n³) 存储空间。事实上只需要上一轮的值，因此一个二维数组就够了：每一轮新值直接原地覆盖旧值。<sup>[4](https://www.usna.edu/Users/cs/wcbrown/courses/S17SI335/notes/05/notes.html)</sup> 每当某一项得到改进时更新前驱指针，事后便可据此重建实际路径。<sup>[5](https://www.cs.umd.edu/~meesh/cmsc351/mount/lectures/lect24-floyd-warshall.pdf)</sup>

## 负权环

算法的正确性论证假设最短路径是简单路径，这在无负权环时成立。负权环会使某些最短路径无定义，因为反复绕行该环可以无限制地降低代价。<sup>[10](https://cp-algorithms.com/graph/all-pair-shortest-path-floyd-warshall.html)</sup> 但算法仍能检测出这种情形：最后一轮结束后，当且仅当存在某个顶点 \( u \) 使 \( d(u,u) < 0 \) 时，图中存在负权环。<sup>[6](https://web.stanford.edu/class/archive/cs/cs161/cs161.1178/notes/bf-fw.pdf)</sup>

实践中还有两个相关事实值得注意。第一，无向图完全不能含有任何负权边，因为沿这样一条边来回走一趟就已经构成负权环。<sup>[10](https://cp-algorithms.com/graph/all-pair-shortest-path-floyd-warshall.html)</sup> 第二，存在负权环时，那些路径能到达该环的顶点对之间的距离会迅速坍缩为很大的负值，因此容许负权环的实现会把最小距离限制在 \(-\text{INF}\) 之类的哨兵值上，以免整数溢出。<sup>[10](https://cp-algorithms.com/graph/all-pair-shortest-path-floyd-warshall.html)</sup> 库实现通常则改为抛出异常：SciPy 的 `floyd_warshall` 抛出 `NegativeCycleError`，NetworkX 抛出 `NetworkXUnbounded`。<sup>[11](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.floyd_warshall.html)</sup><sup> • </sup><sup>[9](https://networkx.org/documentation/latest/_modules/networkx/algorithms/shortest_paths/dense.html)</sup>

## 与其他算法的比较

对于非负权重，全源最短路径可以从每个顶点各运行一次迪杰斯特拉算法求得，在稠密图上总代价为 O(n³)，与弗洛伊德–沃舍尔算法的渐近代价相同。<sup>[4](https://www.usna.edu/Users/cs/wcbrown/courses/S17SI335/notes/05/notes.html)</sup> 实践中弗洛伊德–沃舍尔算法在稠密图上要快得多，因为它的内层循环极其简单。<sup>[4](https://www.usna.edu/Users/cs/wcbrown/courses/S17SI335/notes/05/notes.html)</sup> 与迪杰斯特拉算法不同，它还能直接处理负边权。<sup>[6](https://web.stanford.edu/class/archive/cs/cs161/cs161.1178/notes/bf-fw.pdf)</sup>

对于稀疏图，天平则倾向另一边。约翰逊算法先用贝尔曼–福特算法对图重新赋权，使迪杰斯特拉算法得以适用，其运行时间为 \( O(n^2 \log n + n m) \)，按此标准在稠密图上可能比弗洛伊德–沃舍尔算法更快，但它是稀疏输入下的标准替代方案。<sup>[12](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.weighted.johnson.html)</sup> 2021 年的一项对比研究同样发现，当图不含负边时，从每个源点各运行一次迪杰斯特拉算法在稀疏图上远比弗洛伊德–沃舍尔算法有效。<sup>[13](https://arxiv.org/abs/2109.01872)</sup>

## 历史

该算法可追溯到 20 世纪 60 年代初，并有更早的雏形。1959 年，贝尔纳·鲁瓦在《Comptes rendus》上以《Transitivité et connexité》为题发表了一篇札记，提出了本质上相同的、用于求二元关系传递闭包的步骤；该札记在法国之外流传有限，因而几乎没有引起注意。<sup>[10](https://cp-algorithms.com/graph/all-pair-shortest-path-floyd-warshall.html)</sup><sup> • </sup><sup>[14](https://1024.socinfo.fr/2020/11/1024-numero-16_Article19.pdf)</sup> 1962 年，斯蒂芬·沃舍尔 在《Journal of the ACM》9(1):11–12 上以《A Theorem on Boolean Matrices》为题发表了传递闭包版本，[罗伯特·W·弗洛伊德](https://www.edgepedia.org/zh/robert-w-floyd)同年以单页篇幅的《Algorithm 97: Shortest path》在《Communications of the ACM》5(6):345 上发表了最短路径版本。<sup>[7](https://sigmod.org/publications/dblp/db/journals/jacm/Warshall62.html)</sup><sup> • </sup><sup>[8](https://cir.nii.ac.jp/crid/1362825893844317696)</sup> 同样在 1962 年，彼得·齐拉希·英格曼在同一期刊上描述了如今已成标准的三层嵌套循环形式。<sup>[15](https://learngraphtheory.org/articles/fr/floyd-warshall-algorithm.html)</sup> 沃舍尔感兴趣的是可达性，即判定每一对顶点中一个能否到达另一个；弗洛伊德意识到，只需稍作改动，同样的技术就能计算最短路径。<sup>[5](https://www.cs.umd.edu/~meesh/cmsc351/mount/lectures/lect24-floyd-warshall.pdf)</sup>

## 变体与应用

**传递闭包。** 把每条边的权重赋为 1 再运行弗洛伊德–沃舍尔算法，即可在 Θ(n³) 时间内计算图的传递闭包：所得距离对每一对顶点都回答了其中一个能否到达另一个。<sup>[16](https://mcube.lab.nycu.edu.tw/~cfung/docs/books/cormen2001algorithms.pdf)</sup>

**数值精度。** 权重为实数时，舍入误差会迅速累积：第一阶段引入的误差 δ 在第二阶段可放大为 2δ，第三阶段为 4δ，依此类推。常见的缓解办法是按容差比较，仅当 \( d[i][k] + d[k][j] < d[i][j] - \text{EPS} \) 时才更新。<sup>[10](https://cp-algorithms.com/graph/all-pair-shortest-path-floyd-warshall.html)</sup>

**并行与分块实现。** 由于对 \( k \) 的依赖，三层循环不能随意重排，但把矩阵划分为块、每轮按依赖顺序分四个阶段处理，可使算法对缓存友好且便于并行化。分块弗洛伊德–沃舍尔算法是 GPU 实现的基础；在 Intel Xeon Phi KNL 处理器上的一项优化实现达到了 338 GFLOPS。<sup>[17](https://arxiv.org/abs/1811.01201)</sup>

**期望时间改进。** 对于边权独立且均匀随机取自 [0, 1] 的完全有向图，布罗德尼克、格尔古罗维奇和波扎尔于 2022 年证明，弗洛伊德–沃舍尔算法的两种修改版本——以更聪明的方式安排松弛顺序并避免使用优先队列——可达到期望时间 \( O(n^2 \log^2 n) \)，且这些修改后的算法在实践中与目前已知的最佳算法相比具有竞争力，并胜过其中大多数。<sup>[18](https://www.dlib.si/stream/URN%3ANBN%3ASI%3ADOC-9OFEH90W/08f60c3e-07ab-4af3-8bc8-5ae4a5d143c1/PDF)</sup>

该算法在标准科学计算库中均可调用，包括 SciPy 的 `scipy.sparse.csgraph.floyd_warshall` 和 NetworkX 的 `networkx.floyd_warshall`，二者都返回一个 \( N \times N \) 的距离矩阵，并可选输出前驱信息以重建路径。<sup>[11](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.floyd_warshall.html)</sup><sup> • </sup><sup>[9](https://networkx.org/documentation/latest/_modules/networkx/algorithms/shortest_paths/dense.html)</sup>

## References

1. [Floyd-Warshall algorithm, Dictionary of Algorithms and Data Structures, NIST](https://xlinux.nist.gov/dads/HTML/floydWarshall.html)
2. [networkx.floyd_warshall, NetworkX v0.99 documentation](https://networkx.org/documentation/networkx-0.99/reference/generated/networkx.floyd_warshall.html)
3. [Lecture 11: All-Pairs Shortest Paths, 6.046J Design and Analysis of Algorithms, MIT OpenCourseWare, Spring 2015](https://ocw.mit.edu/courses/6-046j-design-and-analysis-of-algorithms-spring-2015/312f4a419009b58f8147b75975db4347_MIT6_046JS15_lec11.pdf)
4. [SI 335, Unit 5: Graph Search, United States Naval Academy](https://www.usna.edu/Users/cs/wcbrown/courses/S17SI335/notes/05/notes.html)
5. [Lecture 24: Floyd-Warshall Algorithm, CMSC 251 lecture notes, University of Maryland](https://www.cs.umd.edu/~meesh/cmsc351/mount/lectures/lect24-floyd-warshall.pdf)
6. [CS161 Lecture 12: Bellman-Ford and Floyd-Warshall, Stanford University](https://web.stanford.edu/class/archive/cs/cs161/cs161.1178/notes/bf-fw.pdf)
7. [Stephen Warshall: A Theorem on Boolean Matrices, Journal of the ACM 9(1):11-12, 1962, DBLP record](https://sigmod.org/publications/dblp/db/journals/jacm/Warshall62.html)
8. [Robert W. Floyd: Algorithm 97: Shortest path, Communications of the ACM 5(6):345, 1962, CiNii Research record](https://cir.nii.ac.jp/crid/1362825893844317696)
9. [networkx.algorithms.shortest_paths.dense source, NetworkX documentation](https://networkx.org/documentation/latest/_modules/networkx/algorithms/shortest_paths/dense.html)
10. [Floyd-Warshall - finding all shortest paths, Algorithms for Competitive Programming](https://cp-algorithms.com/graph/all-pair-shortest-path-floyd-warshall.html)
11. [scipy.sparse.csgraph.floyd_warshall, SciPy v1.18.0 Manual](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csgraph.floyd_warshall.html)
12. [networkx.johnson, NetworkX 3.7 documentation](https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.shortest_paths.weighted.johnson.html)
13. [Improving The Floyd-Warshall All Pairs Shortest Paths Algorithm, arXiv:2109.01872](https://arxiv.org/abs/2109.01872)
14. [Jean-Claude Derniame: À propos du cheminement dans les graphes, 1024, Bulletin de la Société informatique de France, no. 16 (2020)](https://1024.socinfo.fr/2020/11/1024-numero-16_Article19.pdf)
15. [Floyd-Warshall algorithm explained, Learn Graph Theory](https://learngraphtheory.org/articles/fr/floyd-warshall-algorithm.html)
16. [Introduction to Algorithms (CLRS), Section 25.2, The Floyd-Warshall algorithm](https://mcube.lab.nycu.edu.tw/~cfung/docs/books/cormen2001algorithms.pdf)
17. [Rucci, De Giusti, Naiouf: Blocked All-Pairs Shortest Paths Algorithm on Intel Xeon Phi KNL Processor: A Case Study, arXiv:1811.01201](https://arxiv.org/abs/1811.01201)
18. [Brodnik, Grgurovič, Požar: Modifications of the Floyd-Warshall algorithm with nearly quadratic expected-time, Ars Mathematica Contemporanea 22(1) (2022)](https://www.dlib.si/stream/URN%3ANBN%3ASI%3ADOC-9OFEH90W/08f60c3e-07ab-4af3-8bc8-5ae4a5d143c1/PDF)

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

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

Copyright 2026 Edgepedia

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

Source: https://www.edgepedia.org/zh/floyd-warshall-algorithm

English original: https://www.edgepedia.org/floyd-warshall-algorithm
