Sub topic 24
Floyd-Warshall all-pairs shortest paths
This chapter assumes you know adjacency matrices, edge relaxation, and the basic dynamic programming idea of building a table from smaller subproblems. Dijkstra and Bellman-Ford answer "how far is everything from one source?". Floyd-Warshall answers "how far is every vertex from every other vertex?" in one run. It handles negative edge weights, and it detects negative cycles.
The subproblem
Number the vertices 0 to n-1. Define d_k[i][j] as the length of the shortest path from i to j whose intermediate vertices all come from the set {0, ..., k-1}. Intermediate vertices are the ones strictly between the endpoints.
- With k = 0, no intermediates are allowed.
d_0[i][j]is the direct edge weight, 0 on the diagonal, and infinity where there is no edge. - With k = n, every vertex is allowed.
d_n[i][j]is the true shortest distance.
To go from k to k+1, ask whether the best path may use vertex k. If it does not, the answer is d_k[i][j]. If it does, the path splits at k into an i-to-k part and a k-to-j part. Each part uses only intermediates below k, so each is already known:
d_{k+1}[i][j] = min(d_k[i][j], d_k[i][k] + d_k[k][j])
This is optimal substructure. A shortest path that passes through k contains shortest sub-paths.
The code
The table is updated in place. This is safe because row k and column k do not change during iteration k. Since dist[k][k] is 0 (when there is no negative cycle), the update leaves dist[i][k] and dist[k][j] unchanged.
def floyd_warshall(dist):
n = len(dist)
for k in range(n):
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]
return dist
INF = float('inf')
print(floyd_warshall([[0, 3, INF], [INF, 0, 1], [2, INF, 0]])) # [[0, 3, 4], [3, 0, 1], [2, 5, 0]]The loop over k must be outermost. This is the most common error. If you put k innermost, the table no longer represents "intermediates up to k" and the answers can be wrong.
Complexity
| Quantity | Value |
|---|---|
| Time | Θ(V³), three nested loops over V |
| Space | Θ(V²) for the table, updated in place |
| Input | Adjacency matrix |
Cost is independent of E. On a dense graph with E near V², one run costs about the same as V runs of Dijkstra with a simple array. On a sparse graph, V runs of Dijkstra with a heap cost O(V(V + E) log V) and are asymptotically faster, but only when all weights are non-negative.
Reconstructing paths
The distance matrix does not tell you the route. Keep a second matrix nxt[i][j], the first vertex after i on a shortest path to j. When an update goes through k, set nxt[i][j] = nxt[i][k].
def floyd_warshall_paths(n, edges):
INF = float('inf')
dist = [[INF] * n for _ in range(n)]
nxt = [[None] * 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]:
dist[u][v] = w
nxt[u][v] = v
for k in range(n):
for i in range(n):
if dist[i][k] == INF:
continue
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]
return dist, nxt
def path(nxt, u, v):
if u != v and nxt[u][v] is None:
return []
route = [u]
while u != v:
u = nxt[u][v]
route.append(u)
return route
dist, nxt = floyd_warshall_paths(3, [(0, 1, 3), (1, 2, 1), (2, 0, 2)])
print(dist[0][2], path(nxt, 0, 2)) # 4 [0, 1, 2]The path function is only safe when the graph has no negative cycle. With one, the nxt pointers can form a loop and the while never ends.
Negative edges and negative cycles
Floyd-Warshall is correct with negative edge weights as long as no cycle has negative total weight. If one does, shortest paths are not defined, because you can go around the cycle again and again to lower the cost.
The detection test is simple. After the algorithm finishes, check the diagonal. If dist[i][i] < 0 for any i, vertex i lies on a negative cycle. A vertex on such a cycle has a path back to itself with negative cost, which no cycle-free distance could produce.
Failure modes and gotchas
- Wrong loop order. Putting k anywhere but outermost gives wrong answers.
- Infinity arithmetic. In Python,
inf + (-5)is stillinf, so the code above is safe. In C withINT_MAX, adding to it overflows. Use a large sentinel such as10**9, or skip whendist[i][k]is infinite, as in the second listing. - Diagonal initialization. Set
dist[i][i] = 0. Leaving it at infinity breaks every path that returns through its start. - Undirected graphs with negative edges. Each undirected edge acts as two directed edges, so any negative undirected edge is a negative cycle of length 2.
- Parallel edges. Keep only the smallest weight per ordered pair, as the second listing does.
Choosing an algorithm
| Situation | Best fit |
|---|---|
| One source, non-negative weights | Dijkstra with a heap |
| One source, negative edges allowed | Bellman-Ford, O(VE) |
| All pairs, dense graph or negative edges | Floyd-Warshall, Θ(V³) |
| All pairs, sparse graph, non-negative weights | V runs of Dijkstra |
Floyd-Warshall also computes transitive closure. Replace the distance update with reach[i][j] = reach[i][j] or (reach[i][k] and reach[k][j]) on a boolean matrix (Warshall's algorithm).
Exercise
A graph has two vertices with directed edges 0→1 of weight 1 and 1→0 of weight -2. Initialize the table with zeros on the diagonal and run Floyd-Warshall. What are dist[0][0] and dist[1][1] at the end, and what does this tell you?
Show answer
At k=0, dist[1][1] becomes dist[1][0] + dist[0][1] = -2 + 1 = -1. At k=1, dist[0][0] becomes dist[0][1] + dist[1][0] = 1 + (-2) = -1. Both diagonal entries end at -1, which is negative. A negative diagonal entry shows the graph has a negative cycle (here 0→1→0 with total weight -1), so shortest paths are undefined.
Exercise
Why does the algorithm take Θ(V³) time even when the graph has only V-1 edges?
Show answer
The three nested loops always run V iterations each, and the update for each (k, i, j) triple takes constant time. The work does not depend on how many edges exist, because the input is an adjacency matrix and every cell is examined for every k.