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)\).