TExcelTAD
Home › Graph Algorithms › Shortest Paths as Matrix Multiplication

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: VV runs of Bellman-Ford cost O(V2E)O(V^2 E), which is O(V4)O(V^4) on dense graphs, and VV runs of Dijkstra need non-negative weights. This section develops algorithms designed for all pairs, working on the V×VV \times V 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 1,…,n1, \ldots, n and let W=(wij)W = (w_{ij}) be the weight matrix:

wij={0if i=jw(i,j)if i≠j and (i,j)∈E∞otherwisew_{ij} = \begin{cases} 0 & \text{if } i = j \\ w(i, j) & \text{if } i \ne j \text{ and } (i, j) \in E \\ \infty & \text{otherwise} \end{cases}

Negative weights are allowed; for now assume there is no negative cycle. The output is the matrix D=(dij)D = (d_{ij}) with dij=δ(i,j)d_{ij} = \delta(i, j).

The recurrence

Let lij(m)l_{ij}^{(m)} be the minimum weight of a path from ii to jj that uses at most mm edges. With zero edges, only i=ji = j is possible: lii(0)=0l_{ii}^{(0)} = 0 and lij(0)=∞l_{ij}^{(0)} = \infty otherwise. A path with at most mm edges is a path with at most m−1m - 1 edges to some vertex kk, followed by the edge (k,j)(k, j) (or no edge, which k=jk = j with wjj=0w_{jj} = 0 covers):

lij(m)=min⁡1≤k≤n(lik(m−1)+wkj)l_{ij}^{(m)} = \min_{1 \le k \le n} \left( l_{ik}^{(m-1)} + w_{kj} \right)

Shortest paths have at most n−1n - 1 edges (no negative cycles), so D=L(n−1)=L(n)=L(n+1)=⋯D = L^{(n-1)} = L^{(n)} = L^{(n+1)} = \cdots.

Compare this with the product C=A⋅BC = A \cdot B of ordinary matrices, cij=∑kaikbkjc_{ij} = \sum_k a_{ik} b_{kj}. Replace ∑\sum by min⁡\min and ⋅\cdot by ++, and the recurrence says

L(m)=L(m−1)⊗WL^{(m)} = L^{(m-1)} \otimes W

where ⊗\otimes is the min-plus product. In min-plus algebra ∞\infty plays the role of 0 (it is neutral for min⁡\min) and 0 the role of 1 (neutral for ++), so L(0)L^{(0)} is the identity matrix and L(m)=W⊗mL^{(m)} = W^{\otimes m}, the mm-th min-plus power of WW.

text
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.

python · try it yourself
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 AA shows the growth: with one edge, AA reaches BB and DD; with two, also CC (through BB) and EE (through DD, at weight 7−3=47 - 3 = 4); with three edges a cheaper route to EE through BB and DD appears (2+4−3=32 + 4 - 3 = 3). After n−1=4n - 1 = 4 edges nothing changes any more.

Slow and fast

Computing L(1),L(2),…,L(n−1)L^{(1)}, L^{(2)}, \ldots, L^{(n-1)} one product at a time costs n−2n - 2 products of Θ(n3)\Theta(n^3) each: Θ(n4)\Theta(n^4). But all we need is some power at or beyond n−1n - 1, and the min-plus product is associative (the min⁡\min and ++ operations satisfy the same laws that make ordinary matrix multiplication associative). So square repeatedly:

L(1)=W,L(2)=W⊗W,L(4)=L(2)⊗L(2),…,L(2⌈lg⁡(n−1)⌉)L^{(1)} = W, \quad L^{(2)} = W \otimes W, \quad L^{(4)} = L^{(2)} \otimes L^{(2)}, \quad \ldots, \quad L^{(2^{\lceil \lg(n-1) \rceil})}

That is ⌈lg⁡(n−1)⌉\lceil \lg(n - 1) \rceil products, Θ(n3lg⁡n)\Theta(n^3 \lg n) in total. Overshooting is harmless because L(m)=DL^{(m)} = D for every m≥n−1m \ge n - 1.

python · try it yourself
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 n=32n = 32 the slow method does 30 products and squaring only 5, the factor n−2⌈lg⁡(n−1)⌉\frac{n - 2}{\lceil \lg(n - 1) \rceil}.

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 ii shows up as lii(m)<0l_{ii}^{(m)} < 0 once mm is at least the cycle's length, so after nn steps (or squaring up to a power ≥n\ge n) it suffices to look at the diagonal. The program adds an edge that creates the cycle A→B→C→AA \to B \to C \to A of weight −1-1.

python · try it yourself
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 AA, BB and CC. (With a negative cycle the entries are no longer shortest-path weights, which are −∞-\infty, 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 ∞\infty and a guard so that ∞+w\infty + w stays ∞\infty.

cpp · try it yourself
#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 lij(m)l_{ij}^{(m)} denote?

  1. The weight of the edge from ii to jj
  2. The minimum weight of a path from ii to jj with at most mm edges
  3. The number of paths of length mm
  4. The shortest path through vertex mm

Which two operations replace ++ and ⋅\cdot of ordinary matrix multiplication in EXTEND-SHORTEST-PATHS?

  1. max⁡\max and ++
  2. min⁡\min and ++
  3. min⁡\min and ⋅\cdot
  4. ++ and min⁡\min

What is the running time of the repeated-squaring algorithm for all-pairs shortest paths?

  1. Θ(n4)\Theta(n^4)
  2. Θ(n3lg⁡n)\Theta(n^3 \lg n)
  3. Θ(n3)\Theta(n^3)
  4. Θ(n2lg⁡n)\Theta(n^2 \lg n)

Why may repeated squaring overshoot to L(8)L^{(8)} when n−1=5n - 1 = 5?

  1. Because L(m)=L(n−1)L^{(m)} = L^{(n-1)} for every m≥n−1m \ge n - 1 when there is no negative cycle
  2. Because squaring is approximate
  3. Because L(8)L^{(8)} is cheaper
  4. It may not