Sub topic 11
The Floyd-Warshall Algorithm
This chapter assumes you know the recurrence from the previous chapter. In that recurrence, d_k[i][j] is the shortest i-to-j distance when only vertices 0..k may appear as intermediate stops. You should also be comfortable with Python lists of lists and with math.inf. Here we turn the recurrence into working code, trace it on a small graph, and cover the implementation mistakes that cause most wrong answers. Negative cycle detection and path reconstruction each get their own chapter later.
From Recurrence to Three Loops
The recurrence says:
d_k[i][j] = min(d_{k-1}[i][j], d_{k-1}[i][k] + d_{k-1}[k][j])
A direct translation would keep V + 1 matrices of size V × V, which takes O(V³) memory. Floyd-Warshall keeps one matrix and updates it in place. The algorithm has three parts:
- Initialize a V × V matrix
dist. Setdist[i][i] = 0, setdist[u][v] = wfor each edge, and set every other entry to infinity. - Outer loop over k: allow vertex
kas an intermediate stop. - Inner loops over i and j: for each pair, check whether going through
kbeats the current best.
A Distance-Only Implementation
The version below computes distances only. The full version in the tutorial's reference code also fills a next-hop matrix. That matrix is covered in the path reconstruction chapter.
import math
def floyd_warshall_dist(n, edges):
# n vertices numbered 0..n-1; edges is a list of (u, v, w) tuples
dist = [[math.inf] * n for _ in range(n)]
for i in range(n):
dist[i][i] = 0
for u, v, w in edges:
if w < dist[u][v]: # keep the lightest of parallel edges
dist[u][v] = w
for k in range(n): # k MUST be the outermost loop
row_k = dist[k]
for i in range(n):
d_ik = dist[i][k]
if d_ik == math.inf: # no path i -> k, nothing can improve
continue
row_i = dist[i]
for j in range(n):
cand = d_ik + row_k[j]
if cand < row_i[j]:
row_i[j] = cand
return dist
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
for row in floyd_warshall_dist(4, edges):
print(row)
# [0, 4, 1, 5]
# [inf, 0, -3, 1]
# [inf, inf, 0, 4]
# [inf, inf, inf, 0]Caching row_k, row_i, and d_ik in local variables does not change the algorithm. It saves Python repeated indexing, which matters when the innermost line runs V³ times.
Tracing the Example
The graph has edges 0→1 (4), 0→2 (5), 1→2 (−3), 2→3 (4), and 1→3 (6). The initial matrix is:
| from \ to | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 0 | 4 | 5 | ∞ |
| 1 | ∞ | 0 | −3 | 6 |
| 2 | ∞ | ∞ | 0 | 4 |
| 3 | ∞ | ∞ | ∞ | 0 |
Here is what each round of the outer loop does:
| k | Updates | Reason |
|---|---|---|
| 0 | none | No edge enters vertex 0, so `dist[i][0]` is ∞ for every i ≠ 0 |
| 1 | `dist[0][2]`: 5 → 1, `dist[0][3]`: ∞ → 10 | 0→1→2 costs 4 − 3; 0→1→3 costs 4 + 6 |
| 2 | `dist[0][3]`: 10 → 5, `dist[1][3]`: 6 → 1 | 0→…→2→3 costs 1 + 4; 1→2→3 costs −3 + 4 |
| 3 | none | Vertex 3 has no outgoing edges |
After round k=1, dist[0][3] was 10. That value was correct for paths whose only intermediate stops are 0 and 1. It was wrong for the full graph. Every entry is only guaranteed final after the last round.
Why Updating in Place Is Safe
The recurrence reads values from round k−1. The in-place version may read values that round k has already changed. That causes no error, because the two entries that round k reads, dist[i][k] and dist[k][j], do not change during round k.
To see this, put j = k into the update: dist[i][k] = min(dist[i][k], dist[i][k] + dist[k][k]). When there is no negative cycle through k, dist[k][k] = 0, so the entry stays the same. The same argument applies to dist[k][j] with i = k. Row k and column k stay fixed for the whole round, so reading early or late gives the same result.
Common Errors
Putting k in the wrong loop
The loop order k, i, j is required. If you write i, j, k with k innermost, each dist[i][j] is computed once, as a minimum over single intermediate stops, before the entries it depends on are final. That is one step of a min-plus matrix product, and it only finds paths with a limited number of edges. It sometimes returns the right answer on small graphs by luck, so the bug can pass casual tests. The order of i and j relative to each other does not matter.
Using a finite "infinity"
If you use a large integer such as 10**18 as the sentinel for "no path", then INF + (-3) is less than INF. The algorithm then records a fake path through an unreachable vertex. math.inf avoids this problem because inf + (-3) is still inf. The continue on infinite dist[i][k] also protects against it, but you also need dist[k][j] to be finite. If you must use an integer sentinel, check both terms before adding.
Mishandling parallel edges and self-loops
If the edge list has two edges u→v, keep the smaller weight. Plain assignment would keep whichever edge comes last. A self-loop with a non-negative weight must not overwrite dist[i][i] = 0, and the if w < dist[u][v] check handles that. A self-loop with a negative weight is a negative cycle of length one. It correctly sets dist[i][i] below zero.
Indexing vertices from 1
Floyd-Warshall builds a dense matrix, so vertex labels must map to indices 0..n-1. If your data has labels 1..n or string names, build a dictionary that maps each label to an index first.
Cost and Behavior
| Property | Value |
|---|---|
| Time | Θ(V³), whatever the number of edges |
| Space | Θ(V²) for the matrix |
| Handles negative edges | Yes |
| Handles negative cycles | Detects them, but distances that depend on a cycle are not valid |
| Works on undirected graphs | Yes, add each edge in both directions, but any negative undirected edge forms a negative cycle |
The running time does not depend on how many edges the graph has. That makes Floyd-Warshall a good fit for dense graphs and a poor fit for large sparse ones. In pure Python, V = 500 means 125 million inner-loop steps, which takes tens of seconds. Compiled code or NumPy is far faster. With NumPy you can vectorize each round of k as dist = np.minimum(dist, dist[:, k, None] + dist[None, k, :]), which removes the two inner Python loops. The complexity comparison chapter shows where these costs put Floyd-Warshall relative to running Bellman-Ford or Dijkstra once from each vertex.
Exercises
Exercise
In the example graph, add the edge 3 -> 0 with weight 2. Run Floyd-Warshall by hand or with the code above. What is dist[3][2], and through which path?
Show answer
dist[3][2] = 3, via 3 -> 0 -> 1 -> 2 (2 + 4 - 3). The new cycle 0 -> 1 -> 2 -> 3 -> 0 has weight 4 - 3 + 4 + 2 = 7, which is positive, so the diagonal stays at 0 and all distances are valid.
Exercise
A colleague's version skips the update when dist[i][k] is infinite, but uses INF = 10**9 and does not check dist[k][j]. On which input can this produce a wrong finite distance?
Show answer
The bug appears when dist[i][k] is finite, dist[k][j] is "infinite" (109), and that sum is still less than the stored INF. One case is a negative dist[i][k]. Another is a long chain of negative edges that pulls 109 + dist[i][k] below 109. For example, edges 0 -> 1 with weight -5 and no path from 1 to 2 give dist[0][2] = 109 - 5, a value that looks finite for a pair with no path. Fix it by checking dist[k][j] as well or by using math.inf.
Exercise
Explain why swapping the i and j loops does not change the result, but moving k inside them does.
Show answer
Within one round of k, row k and column k do not change (when there is no negative cycle), so each (i, j) update reads the same inputs in any order. The i and j loops can therefore be swapped. Moving k inside means dist[i][j] is computed once from entries that are not yet final. That breaks the invariant that after round k, every entry is optimal over intermediate stops 0..k.