资源 · 指南或文章
Floyd–Warshall Algorithm
讲解 Floyd-Warshall 全源最短路径算法,只要不存在负环,它就能处理负权边。它的距离表很适合正在学习图上动态规划的候选人。
审核日期
打开原站: Floyd–Warshall Algorithm (在新标签页中打开原网站)练习这个主题打开练习面试官,并带上一道关于 图 的题目。
添加到路线图
把这个资源放进你正在跟进的路线图。它会作为你自己的补充资源显示;路线图的步骤不会改变,也不计入你已记录的步骤。
来源内容语言:英语
In computer science, the Floyd–Warshall algorithm is an algorithm for finding shortest paths in a weighted graph with positive or negative edge weights (but with no negative cycles). A single execution of the algorithm will find the lengths (summed weights) of shortest paths between all pairs of vertices. Although it does not return details of the paths themselves, it is possible to reconstruct the paths with simple modifications to the algorithm. The Floyd–Warshall algorithm compares all possible paths through the graph between each pair of vertices. It is able to do this with O(|V|^3) comparisons in a graph. This is remarkable considering that there may be up to |V|^2 edges in the graph, and every combination of edges is tested. It does so by incrementally improving an estimate on the shortest path between two vertices, until the estimate is optimal. Consider a graph G with vertices V numbered 1 through N. Further consider a function shortestPath(i, j, k) that returns the shortest possible path from i to j using vertices only from the set {1, 2, ..., k} as intermediate points along the way. Now, given this function, our goal is to find the shortest path from each i to each j…
PrepKit 概览
本概览由 PrepKit 编辑根据源代码仓库撰写并审核,并非资源本身的文字。
- 适合人群
- 来源未说明适用级别
- 形式
- 文章
涵盖内容
- 子问题 shortestPath(i, j, k):只允许以顶点 1 到 k 作为中间点时,从 i 到 j 的最短路径
- 给出开销为 O(|V|^3) 次比较
- 一个四顶点示例,给出 k 从 0 到 4 每一步的距离矩阵,包含负权
- 指出该算法只返回路径长度,需要稍作修改才能重建路径
使用建议
这是 PrepKit 的学习建议,并非来源的说法。
根据示例重建 k = 0 的矩阵,自己算出之后的每张表,再与 README 对比。然后编写三重循环,并加上一个下一跳矩阵,以便打印任意两个顶点之间的实际路径。
范围与局限
递推式本身只以从维基百科渲染的图片形式出现,可能难以阅读或复制。提到了负环检测和路径重建,但没有展示。k = 1 的表中有一格只印了一个短横线。
获取方式与形式
GitHub 上采用 MIT 许可的 trekhleb/javascript-algorithms 仓库中的 README;英文,免费阅读。
PrepKit 于 2026年10月2日 审核。 资源来源提交: 85293e3e2b88
本概览的依据
- src/algorithms/graph/floyd-warshall/README.md
收录此条目的页面
订阅 PrepKit 通讯
可选。使用 PrepKit 并不需要订阅。