Shortest Paths as Matrix Multiplication
A navigation app's distance table, a network's latency matrix, the "how far is every city from every other" chart in a road atlas: these need shortest paths between all pairs of vertices. One way is to run a single-source algorithm from every vertex: runs of Bellman-Ford cost , which is on dense graphs, and runs of Dijkstra need non-negative weights. This section develops algorithms designed for all pairs, working on the adjacency matrix. The first is a dynamic program that turns out to be matrix multiplication with the operations changed, and repeated squaring makes it fast.
Setup
Number the vertices and let be the weight matrix:
Negative weights are allowed; for now assume there is no negative cycle. The output is the matrix with .
The recurrence
Let be the minimum weight of a path from to that uses at most edges. With zero edges, only is possible: and otherwise. A path with at most edges is a path with at most edges to some vertex , followed by the edge (or no edge, which with covers):
Shortest paths have at most edges (no negative cycles), so .
Compare this with the product of ordinary matrices, . Replace by and by , and the recurrence says
where is the min-plus product. In min-plus algebra plays the role of 0 (it is neutral for ) and 0 the role of 1 (neutral for ), so is the identity matrix and , the -th min-plus power of .
EXTEND-SHORTEST-PATHS(L, W) // one min-plus product, n^3 additions
1 n = number of rows of L
2 let L' be a new n x n matrix
3 for i = 0 to n - 1
4 for j = 0 to n - 1
5 L'[i][j] = infinity
6 for k = 0 to n - 1
7 L'[i][j] = min(L'[i][j], L[i][k] + W[k][j])
8 return L'The program computes the powers for a five-vertex graph with negative edges and prints them.
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)
idx = {v: i for i, v in enumerate(names)}
W = [[0 if i == j else INF for j in range(n)] for i in range(n)]
for u, v, w in edges:
W[idx[u]][idx[v]] = w
def min_plus(A, B):
return [[min(A[i][k] + B[k][j] for k in range(n)) for j in range(n)] for i in range(n)]
def show(M, title):
print(title)
print(" " + "".join(f"{c:>5}" for c in names))
for i, row in enumerate(M):
print(f" {names[i]} " + "".join(f"{'inf' if x == INF else x:>5}" for x in row))
L = W
show(L, "L(1) = W")
for m in range(2, n):
L = min_plus(L, W)
show(L, f"L({m})")
print("L(5) == L(4):", min_plus(L, W) == L)L(1) = W
A B C D E
A 0 2 inf 7 inf
B inf 0 3 4 inf
C -1 inf 0 inf 2
D inf inf 1 0 -3
E inf 5 inf inf 0
L(2)
A B C D E
A 0 2 5 6 4
B 2 0 3 4 1
C -1 1 0 6 2
D 0 2 1 0 -3
E inf 5 8 9 0
L(3)
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
L(4)
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
L(5) == L(4): True
Row shows the growth: with one edge, reaches and ; with two, also (through ) and (through , at weight ); with three edges a cheaper route to through and appears (). After edges nothing changes any more.
Slow and fast
Computing one product at a time costs products of each: . But all we need is some power at or beyond , and the min-plus product is associative (the and operations satisfy the same laws that make ordinary matrix multiplication associative). So square repeatedly:
That is products, in total. Overshooting is harmless because for every .
import random
INF = float("inf")
def min_plus(A, B, counter):
n = len(A)
counter[0] += n ** 3
return [[min(A[i][k] + B[k][j] for k in range(n)) for j in range(n)] for i in range(n)]
def slow(W):
c = [0]
L = W
for _ in range(len(W) - 2):
L = min_plus(L, W, c)
return L, c[0]
def fast(W):
c = [0]
L, m = W, 1
while m < len(W) - 1:
L = min_plus(L, L, c)
m *= 2
return L, c[0]
rng = random.Random(30)
print(f"{'n':>4} {'slow additions':>15} {'squaring':>10} {'products':>9}")
for n in [8, 16, 32]:
h = [rng.randint(0, 20) for _ in range(n)] # potentials: negative edges, no negative cycle
W = [[0 if i == j else (rng.randint(1, 9) + h[i] - h[j] if rng.random() < 0.3 else INF)
for j in range(n)] for i in range(n)]
A, ca = slow(W)
B, cb = fast(W)
assert A == B
print(f"{n:>4} {ca:>15,} {cb:>10,} {cb // n ** 3:>9}") n slow additions squaring products
8 3,072 1,536 3
16 57,344 16,384 4
32 983,040 163,840 5
For the slow method does 30 products and squaring only 5, the factor .
Negative cycles on the diagonal
If the graph has a negative cycle, the powers keep decreasing: going around the cycle again with more edges allowed helps. A negative cycle through shows up as once is at least the cycle's length, so after steps (or squaring up to a power ) it suffices to look at the diagonal. The program adds an edge that creates the cycle of weight .
INF = float("inf")
names = "ABCDE"
edges = [("A", "B", 2), ("A", "D", 7), ("B", "C", -2), ("B", "D", 4), ("C", "A", -1),
("C", "E", 2), ("D", "C", 1), ("D", "E", -3), ("E", "B", 5)]
n = len(names)
W = [[0 if i == j else INF for j in range(n)] for i in range(n)]
for u, v, w in edges:
W[names.index(u)][names.index(v)] = w
L, m = W, 1
while m < n:
L = [[min(L[i][k] + L[k][j] for k in range(n)) for j in range(n)] for i in range(n)]
m *= 2
print(f"diagonal of L({m}):", {names[i]: L[i][i] for i in range(n)})
print("negative cycle through:", [names[i] for i in range(n) if L[i][i] < 0])diagonal of L(8): {'A': -2, 'B': -2, 'C': -2, 'D': 0, 'E': 0}
negative cycle through: ['A', 'B', 'C']
Every vertex on a negative cycle ends with a negative diagonal entry; here , and . (With a negative cycle the entries are no longer shortest-path weights, which are , but the diagonal test is still sound.)
In C++
The C++ version computes all-pairs distances by repeated min-plus squaring, with a large sentinel for and a guard so that stays .
#include <algorithm>
#include <cstdio>
#include <vector>
using Matrix = std::vector<std::vector<long long>>;
const long long INF = 1LL << 50;
Matrix min_plus(const Matrix& a, const Matrix& b) {
const size_t n = a.size();
Matrix c(n, std::vector<long long>(n, INF));
for (size_t i = 0; i < n; ++i)
for (size_t k = 0; k < n; ++k) {
if (a[i][k] >= INF) continue;
for (size_t j = 0; j < n; ++j)
if (b[k][j] < INF) c[i][j] = std::min(c[i][j], a[i][k] + b[k][j]);
}
return c;
}
int main() {
const int n = 5; // A..E
Matrix w(n, std::vector<long long>(n, INF));
for (int i = 0; i < n; ++i) w[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}})
w[e.u - 'A'][e.v - 'A'] = e.w;
Matrix l = w;
int products = 0;
for (int m = 1; m < n - 1; m *= 2) { l = min_plus(l, l); ++products; }
std::printf("%d squarings\n ", products);
for (int j = 0; j < n; ++j) std::printf("%4c", 'A' + j);
std::printf("\n");
for (int i = 0; i < n; ++i) {
std::printf("%c ", 'A' + i);
for (int j = 0; j < n; ++j) std::printf("%4lld", l[i][j]);
std::printf("\n");
}
}2 squarings
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
Test yourself
What does denote?
- The weight of the edge from to
- The minimum weight of a path from to with at most edges
- The number of paths of length
- The shortest path through vertex
Which two operations replace and of ordinary matrix multiplication in EXTEND-SHORTEST-PATHS?
- and
- and
- and
- and
What is the running time of the repeated-squaring algorithm for all-pairs shortest paths?
Why may repeated squaring overshoot to when ?
- Because for every when there is no negative cycle
- Because squaring is approximate
- Because is cheaper
- It may not