Floyd-Warshall Algorithm
Dijkstra and Bellman-Ford answer: what is the cheapest route from one source to everywhere? But what if you need the cheapest route between every pair of nodes? You could run Dijkstra V times — or you could use Floyd-Warshall, a clean dynamic programming algorithm that solves all pairs in one pass.
Floyd-Warshall handles negative edge weights (but not negative cycles). It is ideal for small, dense graphs where you need a complete distance matrix — a table showing the shortest distance from every node to every other node.
The DP recurrence
For each possible intermediate node k, check whether routing through k makes the path from i to j cheaper.
After all V outer iterations, dist[i][j] holds the shortest distance from node i to node j through any combination of intermediate nodes.
← → arrow keys to step · click elements to interact
Floyd-Warshall: All-Pairs Shortest Paths
Tracing a 4-node example
Nodes: A, B, C, D. Edges: A→B=3, B→C=2, A→C=10, C→D=1, B→D=8.
Initially dist[A][D] = ∞ (no direct edge). After considering B as intermediate: dist[A][B] + dist[B][D] = 3+8 = 11 — update. After considering C: dist[A][C] + dist[C][D] = 5+1 = 6 (A→B→C = 5) — update to 6. Final shortest path A→D is 6, via A→B→C→D.
Negative cycle detection
After the algorithm, check the diagonal. dist[i][i] should always be 0. If dist[i][i] < 0, there is a negative-weight cycle passing through node i — the shortest path is undefined.
When to use Floyd-Warshall
- V is small (up to a few hundred nodes) — \(O(V^3)\) becomes too slow for thousands
- You need the shortest distance between all pairs, not just from one source
- The graph may have negative edge weights (but no negative cycles)
For large sparse graphs, running Dijkstra from each node is usually faster: \(O(V × (V+E)\) log V) vs \(O(V^3)\).