Floyd-Warshall: all pairs in O(V³)
1 A distance chart for every pair
Dijkstra and Bellman-Ford find the shortest distance from one town to every other town. Some questions ask about every pair of towns. A road atlas answers those with a distance chart at the back: a row and a column for every town, and the shortest distance in each cell.
Here are four towns joined by one-way roads, with lengths in km. The chart starts with what we know without any planning: 0 on the diagonal, each direct road's length, and ∞ where no direct road exists.
The chart is wrong in places. It says 0 to 3 is 10 km, by the direct road, but 0 → 1 → 2 → 3 is 3 + 1 + 1 = 5 km. It says 1 cannot reach 0, but 1 → 2 → 3 → 0 gets there.
Running Dijkstra from every town would fix the chart. Floyd-Warshall fixes it with three loops over the chart itself, and negative roads do not break it.
2 One more stopover at a time
We fix the chart in rounds, one per town. In round k, a route may also pass through town k as a stopover, a town in its middle. After round 0, routes may stop at town 0. After round 1, they may stop at towns 0 and 1. After the last round, they may stop anywhere, so the chart is final.
In round k, each cell asks one question: is the route shorter through k? That route has two parts, i to k and k to j, and both are already in the chart. In round 2, the chart says 0 to 2 is 4 km. Round 1 found that, through town 1. The road from 2 to 3 is 1 km, so 0 to 3 through town 2 is 5, shorter than the 7 the chart holds.
With dist as the chart, the round's update is:
This is relaxing, as in the last two lessons, with a town in the middle instead of a road. Bellman-Ford's rounds let a route use one more road each time. Here each round lets it use one more town.
Why both parts are already right. The best route from i to j that stops only at towns 0 to k passes k at most once, because a loop only adds length. Section 5 covers loops of negative length. If the route skips k, round k − 1 already found it. If it passes k, neither part has k in its middle. So round k − 1 already left the best parts in dist[i][k] and dist[k][j].
Round k needs all of round k − 1 to be finished. That is why k is the outer loop.
3 Filling the chart round by round
Here are the four rounds on our map. Town k is filled in, and the cells that got shorter in that round are highlighted:
Each new number is a cell from column k plus a cell from row k. In round 3, 1 to 0 becomes dist[1][3] + dist[3][0] = 2 + 3 = 5. The 2 came from round 2, so each round builds on the rounds before it.
One cell, 0 to 3, improves twice:
| Round k | dist[0][k] | dist[k][3] | Through k | dist[0][3] |
|---|---|---|---|---|
| start | 10 | |||
| 0 | 0 | 10 | 10 | 10 |
| 1 | 3 | 4 | 7 | 7 |
| 2 | 4 | 1 | 5 | 5 |
| 3 | 5 | 0 | 5 | 5 |
Round 1 finds 0 → 1 → 3. Round 2 finds 0 → 1 → 2 → 3, using the 4 that round 1 put into dist[0][2]. In rounds 0 and 3, k is one end of the route, so one part is 0 km and nothing changes.
That last point also means row k and column k never change during round k. So the code can update the one chart in place.
4 The code
The code builds the chart from the edge list, then runs the three loops with k outermost. INF stands for ∞. It is 10⁹, larger than any real distance, and the code skips an update when either part is INF. The second function checks the diagonal, for the reason in section 5.
C++
INF is 10⁹, not INT_MAX. INT_MAX + 3 overflows, and the result is usually a large negative number that wins every min. 10⁹ + 10⁹ still fits in an int, and the guard means we never add INF anyway.
INF is 10⁹, not Integer.MAX_VALUE. Integer.MAX_VALUE + 3 wraps around to −2,147,483,646 without any error, and that number wins every Math.min. 10⁹ + 10⁹ still fits in an int.
Integers never overflow, so any large INF is safe. float('inf') also works, but it mixes a float into a chart of integers, so a plain 10⁹ keeps the answers as int.
Infinity would also work, because Infinity + 3 and Infinity - 2 are both still Infinity. We keep 10⁹, so the chart holds only whole numbers.
int is 64 bits on today's machines, so INF + INF fits. The guard still matters when a road is negative, as the mistakes section shows.
Overflow stops the program. In a debug build, i32::MAX + 3 panics, which is a Runtime Error. 10⁹ + 10⁹ fits in an i32, and the guard means we never add INF anyway.
INF is 10⁹, not int.MaxValue. int.MaxValue + 3 wraps around to −2,147,483,646 without any error, and that number wins every Math.Min. 10⁹ + 10⁹ still fits in an int.
For our map, printing the chart and then hasNegativeCycle gives:
0 3 4 5
5 0 1 2
4 7 0 1
3 6 7 0
false
The build takes the smaller length when two roads join the same pair of towns. That is why it uses min instead of writing w straight in.
5 Negative roads and negative cycles
Floyd-Warshall never assumes that a route only gets longer. Change the road 3 → 0 to −2 km, a road where drivers get paid. The same loops give a correct chart: 1 to 0 becomes 1 + 1 − 2 = 0, and 3 to 0 becomes −2.
A negative cycle is a loop of roads whose lengths add up to less than 0. Change 3 → 0 to −6 instead. The loop 0 → 1 → 2 → 3 → 0 is now 3 + 1 + 1 − 6 = −1. Each trip round it makes a route 1 km shorter, so no route is the shortest.
The chart shows this on its diagonal. dist[i][i] starts at 0, and it drops only when some loop from i back to i adds up to less than 0:
So after the loops, any dist[i][i] < 0 means a negative cycle. On this map, hasNegativeCycle prints true. The other cells are not distances any more, because each one depends on how many times the loops happened to go round the cycle.
6 Reachability and the route itself
Can i reach j at all? Some problems ask only that. The chart then holds true or false, and i reaches j when i reaches k and k reaches j:
This chart is the transitive closure of the graph, and it takes the same three loops.
Which towns are on the route? The chart holds lengths, not routes. A second chart, next, holds the first town after i on the best route from i to j. When k improves a cell, the route to j now starts the same way as the route to k:
for each road (u, v, w)
next[u][v] = v
when round k improves dist[i][j]
next[i][j] = next[i][k]
route from i to j, if dist[i][j] < INF
route = [i]
while i != j
i = next[i][j]
add i to route
On our map, next[0][3] is 1, next[1][3] is 2 and next[2][3] is 3. So the route from 0 to 3 is 0 → 1 → 2 → 3.
7 Mistakes
- k as an inner loop. With the loops in the order i, j, k, our map gives
dist[1][0]= 7 instead of 5. Cell [1][0] is decided once, at the start of row 1. Thendist[1][3]still holds the direct road of 4 km, because cell [1][3] comes later. So the code adds 4 + 3 and never comes back. - An INF that overflows. With
INT_MAXasINFand no guard, round 0 addsdist[1][0] + dist[0][1], which isINF+ 3. In a 32-bitintthat wraps to −2,147,483,646, anddist[1][1]takes that value. - No guard with negative roads. Even with
INF= 10⁹,INF+ (−2) is less thanINF. Without the guard, a town no road reaches gets a "distance" just underINF. - Forgetting
dist[i][i] = 0. Each diagonal cell then ends as the shortest round trip instead of 0. On our map,dist[0][0]comes out as 8, the loop 0 → 1 → 2 → 3 → 0. - Two-way roads added one way. In an undirected graph, each edge [u, v, w] fills both
dist[u][v]anddist[v][u]. With n = 2 and edges = [[0, 1, 2]], one way leavesdist[1][0]atINFinstead of 2. - Two roads between the same towns. With the roads [0, 1, 2] and then [0, 1, 7], writing
wstraight in leavesdist[0][1]at 7 instead of 2.
8 Cost and when to use it
Three loops of V each make V³ steps. The chart takes V² cells.
- V = 400. That is 6.4 × 10⁷ steps, well within a second at about 10⁸ steps a second. The chart has 1.6 × 10⁵ cells.
- V = 10⁵. That is 10¹⁵ steps, far past the time limit, so it gets Time Limit Exceeded (TLE). The chart alone needs 10¹⁰ cells, more memory than any problem allows.
The other way to fill the chart is Dijkstra from every town:
| Floyd-Warshall | Dijkstra from every town | |
|---|---|---|
| Time | O(V³) | O(V · E log V) |
| Negative roads | Allowed | Not allowed |
| Code | Three loops | A heap, run V times |
| Fits | V up to about 400 | Larger, sparse graphs |
On a dense graph, E is close to V², and V runs of Dijkstra cost more than Floyd-Warshall.
The signs that a problem wants Floyd-Warshall:
- Distances between many pairs, not from one start. Find the City With the Smallest Number of Neighbors at a Threshold Distance needs every city's distance to every other city, with at most 400 cities.
- A small V, a few hundred at most. The constraints say this before anything else.
- Negative roads and all pairs together. Dijkstra cannot take negative roads, and V runs of Bellman-Ford are too slow.
With one start, as in Network Delay Time, Dijkstra is the right tool. The next lesson, on 0-1 BFS, covers roads that cost only 0 or 1.
Practice it
- Network Delay TimeMedium
- Path With Minimum EffortMedium
- Cheapest Flights Within K StopsMedium
- Swim in Rising WaterHard
- Find the City With the Smallest Number of Neighbors at a Threshold DistanceMedium
- Word Ladder IIHard
- Shortest path in a DAGMedium
- Dijkstra's algorithmMedium
- Print the shortest pathMedium
- Number of Ways to Arrive at DestinationMedium
- Path with Maximum ProbabilityMedium
- Minimum multiplications to reach the endHard
- Bellman-Ford algorithmMedium
- Floyd-Warshall algorithmHard
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.