D'abord le quiz du chapitre 2D'abord, vérifiez le chapitre 2
Faites le quiz du chapitre 2 : 10 questions, réussi avec 7 bonnes réponses. Vous pouvez le refaire autant de fois que vous voulez.
Every Pair at Once
Chapitre 3, leçon 3 sur 4
Floyd-Warshall: shortest paths between all pairs, in one table.
Narration en anglais. Activez les sous-titres anglais, arabes, allemands, espagnols ou français ci-dessus.
Leçon écrite
8 min de lectureRédigée en anglais.
Many road atlases end with a table: the distance between every pair of cities, ready to read at a glance. Dijkstra's algorithm fills one row of that table per run. To fill every row, you could run it again from each city.
In 1962 Robert Floyd published a shorter way, in a note of just a few lines, built on a theorem by Stephen Warshall: three nested loops fill the whole table at once. This lesson covers the one idea behind Floyd-Warshall, a run by hand, why the order of the loops matters, how it spots a negative cycle, and how to rebuild the routes.
Every pair
On lesson 10's sketch map of the Netherlands, one Dijkstra run from Rotterdam gives one row of the atlas table. Fourteen cities need fourteen runs.
One Dijkstra run fills one row of the atlas table.
Running Dijkstra from every vertex is correct, as long as no weight is negative. With a heap it costs V times O(E log V).
- On a sparse graph, like a road network, that is the right choice.
- On a dense graph, where almost every pair is linked, E grows towards V², and the total grows towards V³ log V.
Floyd-Warshall takes V³ steps on every graph, accepts negative edges as they are, and needs no heap at all: just a table and three loops.
One more stop
The trick is to ask a narrower question. Number the vertices from 1 to V, and ask:
- With k = 0, no stops are allowed, so the answer is the direct edge, or infinity.
- With k = V, every stop is allowed, and the answer is the true distance.
Now let one more vertex, k, join the allowed stops. The best route either avoids k, and nothing changes, or it passes through k. If it passes through k, it does so exactly once, because a shortest route never repeats a vertex. So it splits into a leg from i to k and a leg from k to j, and neither leg stops at k. Both legs are already in the table from the previous round.
That gives the whole algorithm in one line:
Avoid k, or pass through it once.
This is dynamic programming: every small answer is computed once, stored in the table, and reused to build bigger ones.
Run it by hand
The example from our guide has four vertices and four directed edges: 1 → 2 (5), 1 → 4 (10), 2 → 3 (3) and 3 → 4 (1).
The starting table holds the direct edges, zeros on the diagonal, and infinity everywhere else.
The starting table: direct edges only.
- Round 1 allows vertex 1 as a stop. No edge leads into vertex 1, so nothing changes.
- Round 2 allows vertex 2. 1 → 2 costs 5 and 2 → 3 costs 3, so d(1, 3) drops from ∞ to 8.
- Round 3 allows vertex 3. d(1, 4) drops from 10 to 8 + 1 = 9, reusing the 8 we just found, and d(2, 4) becomes 3 + 1 = 4.
- Round 4 changes nothing, because vertex 4 has no way out.
| From \ To | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 1 | 0 | 5 | 8 | 9 |
| 2 | ∞ | 0 | 3 | 4 |
| 3 | ∞ | ∞ | 0 | 1 |
| 4 | ∞ | ∞ | ∞ | 0 |
Round 3: 1 to 4 becomes 9 and 2 to 4 becomes 4.
The infinities that remain are real: nothing can ever reach vertex 1, for example. That was 4 × 4 × 4 = 64 tests for four vertices: V³, however many edges there are. With all twelve possible edges it would cost exactly the same.
Loop order
We used a single table, overwriting it as we went. That is safe: during round k, row k and column k never change, because d(k, k) = 0, and a detour from k back to k adds nothing.
But the order of the loops is not free. The loop over k must be the outermost one. Put it innermost, and some pairs are finished before the legs they need exist.
Swap the names of vertices 3 and 4 in our example, so the edges are 1 → 2 (5), 1 → 3 (10), 2 → 4 (3) and 4 → 3 (1). With k innermost, the pair (1, 3) is settled while d(1, 4) is still unknown, so it reports the direct 10 instead of 9.
With k innermost, the pair 1 to 3 is finished too early.
The code runs without an error, and the numbers look reasonable. That is exactly what makes this bug so dangerous.
Negative weights
Negative edges are no problem: nothing in the rule assumes that an extra edge makes a route longer. On the graph from two lessons ago (s → a 2, s → b 5, b → a −4, a → t 1), Floyd-Warshall finds s to t at 2, just like Bellman-Ford.
A negative cycle is different, and the table reports it for free. The diagonal starts at zero, and a vertex can only reach a negative distance to itself by going round a loop with a negative total. On last lesson's triangle (weights 2, −5 and 1), every diagonal entry turns negative.
Read the diagonal: every vertex on the cycle turns negative.
The routes
The table gives distances, not routes. For the routes, keep a second table called next: next(i, j) is the first step on the best route from i to j.
- Start with next(i, j) = j wherever a direct edge exists.
- When a route through k wins, set next(i, j) = next(i, k): copy the first step of the route to k, not k itself.
To read a route, start at i and keep following next until you reach j. From 1 to 4: next(1, 4) = 2, next(2, 4) = 3, next(3, 4) = 4. So the route is 1, 2, 3, 4, and 5 + 3 + 1 = 9.
The next table, and the route from 1 to 4.
Cost and cousins
The cost never changes: V³ tests and a V × V table. A thousand vertices means a billion tests. That is fine for a computer, but it grows fast.
The same three loops solve other problems too:
- Reachability (Warshall's version). Replace the sum with a logical and and the minimum with a logical or: reach(i, j) becomes reach(i, j) or (reach(i, k) and reach(k, j)). The result says which vertex can reach which.
- Widest route. Replace the sum with a minimum and the minimum with a maximum: the best route is the one whose narrowest link is as wide as possible, for bandwidth or road capacity. Reading our example's weights as capacities, the widest route from 1 to 4 is the direct edge (10), because the route through 2 and 3 is only as wide as its narrowest link, 1.
In Python, the heart of it is three loops and one comparison. This version also keeps the next table:
INF = float("inf")
def floyd_warshall(n, edges):
dist = [[0 if i == j else INF for j in range(n)] for i in range(n)]
nxt = [[None] * n for _ in range(n)]
for u, v, w in edges:
dist[u][v] = w
nxt[u][v] = v
for k in range(n): # k must be the outer loop
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
nxt[i][j] = nxt[i][k]
if any(dist[i][i] < 0 for i in range(n)):
raise ValueError("negative cycle")
return dist, nxt
def route(nxt, i, j):
path = [i]
while i != j:
i = nxt[i][j]
path.append(i)
return path
# vertices 1 to 4 are stored as 0 to 3
dist, nxt = floyd_warshall(4, [(0, 1, 5), (0, 3, 10), (1, 2, 3), (2, 3, 1)])
dist[0] # [0, 5, 8, 9]
route(nxt, 0, 3) # [0, 1, 2, 3]
Three loops and one comparison.
Key ideas
- Floyd-Warshall finds the shortest distance between every pair of vertices, in one table.
- Round k lets vertex k become a stop, and each pair keeps the better of its old distance and the two legs through k.
- The loop over k must be outermost. A negative diagonal entry reveals a negative cycle, and a next table rebuilds the routes.
- It always takes V³ time: ideal for dense graphs, and for when you really need every pair.
Check yourself
1. Add the edge 4 → 1 with weight 2 to the example. What is the distance from 3 to 2 now?
2. A graph has 50 vertices and 60 edges, all weights positive, and you need every pair. Which is the better choice, and roughly how many basic steps does Floyd-Warshall take?
3. After running Floyd-Warshall, the diagonal is 0, 0, −3, 0. What does that tell you?
Practice on the platform
The Floyd-Warshall guide walks through this example one round at a time. In the Floyd-Warshall visualizer, import the four edges and run it: 1 to 4 drops from ten to nine in round three, through 2 and 3, exactly as we found by hand.
À suivre