The Floyd-Warshall Algorithm
Repeated squaring indexes its dynamic program by the number of edges on a path and pays . The Floyd-Warshall algorithm (1962) indexes it by which vertices a path may pass through, and gets all-pairs shortest paths in time with three nested loops and a single matrix updated in place. It allows negative edges, detects negative cycles, and is so short that it is often the first choice whenever is a few hundred.
Intermediate vertices
The intermediate vertices of a simple path are , all of them except the two ends. Number the vertices and let
With no intermediate vertex is allowed, so , the weight matrix. With every path is allowed, so .
The recurrence. Assume no negative cycle and take a lightest path from to with intermediate vertices in ; it can be taken simple. Either is not an intermediate vertex of , and then all of 's intermediate vertices are in ; or is, exactly once, and splits into and , both using only as intermediates, and both lightest such paths by optimal substructure. Hence
FLOYD-WARSHALL(W, n)
1 D = a copy of W // D[i][j] = w_ij, 0 on the diagonal, infinity if no edge
2 for k = 0 to n - 1 // allow vertex k as an intermediate
3 for i = 0 to n - 1
4 for j = 0 to n - 1
5 if D[i][k] + D[k][j] < D[i][j]
6 D[i][j] = D[i][k] + D[k][j]
7 return DOne matrix is enough. The recurrence uses the matrix of round , but the code overwrites entries during round . That is safe because row and column do not change in round : , and without negative cycles. So line 5 reads the same values whether they are "old" or "new".
Running time. Three nested loops of iterations with work inside: , with space.
Watching it work
The animation shows the distance matrix (row = from, column = to) on the graph from the previous lesson. Each round allows one more vertex as an intermediate, and each frame is one improvement.
The Python version prints the same improvements in the same order.
INF = float("inf")
names = "ABCDE"
edges = [("A", "B", 2), ("A", "D", 7), ("B", "C", 3), ("B", "D", 4), ("C", "A", -1),
("C", "E", 2), ("D", "C", 1), ("D", "E", -3), ("E", "B", 5)]
n = len(names)
D = [[0 if i == j else INF for j in range(n)] for i in range(n)]
nxt = [[None] * n for _ in range(n)] # first step of a shortest path i -> j
for u, v, w in edges:
i, j = names.index(u), names.index(v)
D[i][j], nxt[i][j] = w, j
updates = 0
for k in range(n):
print(f"round {names[k]}:", end="")
for i in range(n):
for j in range(n):
if D[i][k] + D[k][j] < D[i][j]:
print(f" {names[i]}{names[k]}{names[j]}={D[i][k] + D[k][j]}", end="")
D[i][j] = D[i][k] + D[k][j]
nxt[i][j] = nxt[i][k]
updates += 1
print()
print(f"{updates} improvements")
print(" " + "".join(f"{c:>4}" for c in names))
for i in range(n):
print(f" {names[i]} " + "".join(f"{D[i][j]:>4}" for j in range(n)))
def path(i, j):
p = [i]
while i != j:
i = nxt[i][j]
p.append(i)
return "".join(names[x] for x in p)
print("path E -> A:", path(4, 0), " path A -> E:", path(0, 4))round A: CAB=1 CAD=6
round B: ABC=5 ABD=6 CBD=5 EBC=8 EBD=9
round C: ACE=7 BCA=2 BCE=5 DCA=0 DCB=2 ECA=7
round D: ADE=3 BDE=1
round E:
15 improvements
A B C D E
A 0 2 5 6 3
B 2 0 3 4 1
C -1 1 0 5 2
D 0 2 1 0 -3
E 7 5 8 9 0
path E -> A: EBCA path A -> E: ABDE
Each printed triple means that the route from to through is better than any found before. The final matrix equals the one repeated squaring produced, after 25 additions per round instead of 125 per product.
Reconstructing paths
The program keeps a successor matrix nxt: nxt[i][j] is the first vertex after on a best known path to . When the path through wins, the first step toward becomes the first step toward . Following nxt from until reaching prints the path in time. The textbook alternative is a predecessor matrix , with the vertex before on the path; the update is then . Both cost extra space.
Negative cycles and a test
If there is a negative cycle, the diagonal entry of some vertex on it becomes negative during the run, just as with repeated squaring: when the cycle's highest-numbered vertex is allowed, the path from a cycle vertex around the cycle back to itself is found. So a negative cycle exists if and only if some at the end. The program checks Floyd-Warshall against runs of Bellman-Ford on random graphs with negative edges, and checks the diagonal test on graphs that do have negative cycles.
import random
INF = float("inf")
def floyd_warshall(n, edges):
D = [[0 if i == j else INF for j in range(n)] for i in range(n)]
for u, v, w in edges:
D[u][v] = min(D[u][v], w)
for k in range(n):
Dk = D[k]
for i in range(n):
dik = D[i][k]
if dik == INF:
continue
Di = D[i]
for j in range(n):
if dik + Dk[j] < Di[j]:
Di[j] = dik + Dk[j]
return D
def bellman_ford(n, edges, s):
d = [INF] * n; d[s] = 0
for _ in range(n - 1):
for u, v, w in edges:
if d[u] + w < d[v]:
d[v] = d[u] + w
negative = any(d[u] + w < d[v] for u, v, w in edges)
return d, negative
rng = random.Random(8)
agree = detected = 0
for trial in range(300):
n = rng.randint(2, 10)
h = [rng.randint(0, 10) for _ in range(n)]
with_cycle = trial % 3 == 0
edges = []
for u in range(n):
for v in range(n):
if u != v and rng.random() < 0.3:
w = rng.randint(0, 9) + h[u] - h[v] # no negative cycle by construction
edges.append((u, v, w - (12 if with_cycle and rng.random() < 0.2 else 0)))
D = floyd_warshall(n, edges)
neg_fw = any(D[i][i] < 0 for i in range(n))
runs = [bellman_ford(n, edges, s) for s in range(n)]
neg_bf = any(neg for _, neg in runs)
assert neg_fw == neg_bf
if neg_fw:
detected += 1
else:
assert all(D[s] == runs[s][0] for s in range(n))
agree += 1
print(f"{agree} graphs: Floyd-Warshall equals one Bellman-Ford run per source")
print(f"{detected} graphs: both methods report a negative cycle")246 graphs: Floyd-Warshall equals one Bellman-Ford run per source
54 graphs: both methods report a negative cycle
The practice problem All-Pairs Shortest Paths asks for the full distance matrix.
In C++
The C++ version is the triple loop itself; the INF checks keep from overflowing or becoming finite.
#include <cstdio>
#include <vector>
int main() {
const int n = 5;
const long long INF = 1LL << 50;
std::vector<std::vector<long long>> d(n, std::vector<long long>(n, INF));
for (int i = 0; i < n; ++i) d[i][i] = 0;
struct E { char u, v; int w; };
for (E e : {E{'A','B',2}, E{'A','D',7}, E{'B','C',3}, E{'B','D',4}, E{'C','A',-1},
E{'C','E',2}, E{'D','C',1}, E{'D','E',-3}, E{'E','B',5}})
d[e.u - 'A'][e.v - 'A'] = e.w;
int updates = 0;
for (int k = 0; k < n; ++k)
for (int i = 0; i < n; ++i) {
if (d[i][k] >= INF) continue;
for (int j = 0; j < n; ++j)
if (d[k][j] < INF && d[i][k] + d[k][j] < d[i][j]) { d[i][j] = d[i][k] + d[k][j]; ++updates; }
}
std::printf("%d improvements\n", updates);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) std::printf("%4lld", d[i][j]);
std::printf("\n");
}
bool negative = false;
for (int i = 0; i < n; ++i) negative |= d[i][i] < 0;
std::printf("negative cycle: %s\n", negative ? "yes" : "no");
}15 improvements
0 2 5 6 3
2 0 3 4 1
-1 1 0 5 2
0 2 1 0 -3
7 5 8 9 0
negative cycle: no
Test yourself
What does mean in Floyd-Warshall?
- The shortest path with at most edges
- The shortest path from to whose intermediate vertices all lie in
- The -th shortest path
- The distance from to
Why can Floyd-Warshall update its matrix in place?
- Because the matrix is symmetric
- Because row and column do not change during round , so the values read on line 5 are the same old or new
- Because the loops run backwards
- It cannot; it needs two matrices
After Floyd-Warshall, for some vertex . What does this tell you?
- Vertex is unreachable
- Vertex lies on a negative-weight cycle
- The weights are all negative
- Nothing
What are the time and space of Floyd-Warshall on vertices?
- time, space
- time, space
- time, space
- time