Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

All-Pairs Shortest Paths

Floyd–Warshall, min-plus products and the APSP conjecture.

Floyd–Warshall's three nested loops, from 1962, are still essentially the best way to compute all-pairs shortest paths on dense weighted graphs: every algorithm found since shaves off less than any polynomial factor. That stubbornness hardened into a hypothesis, the APSP conjecture, and many other problems turned out to be exactly as hard.

What you’ll learn

  • Prove Floyd–Warshall correct by dynamic programming over intermediate vertices, explain why one matrix updated in place suffices, and detect negative cycles.
  • Express all-pairs shortest paths through the min-plus matrix product, compute it by repeated squaring, and explain why fast matrix multiplication does not apply directly.
  • Derive Seidel's O(nωlog⁡n)O(n^{\omega}\log n) algorithm for unweighted undirected graphs.
  • State the APSP conjecture, Williams's n3/2Ω(log⁡n)n^3 / 2^{\Omega(\sqrt{\log n})} algorithm, and the subcubic equivalences of Vassilevska Williams and Williams.

Floyd–Warshall, proved

DerivationThe recurrence, assuming no negative cycle
  1. weight=D(k−1)[i][j]\text{weight} = D^{(k-1)}[i][j]

    Without negative cycles, a best path from ii to jj through {1,…,k}\{1, \dots, k\} can be taken simple. If it avoids kk, its intermediate vertices lie in {1,…,k−1}\{1, \dots, k - 1\}:

  2. weight=D(k−1)[i][k]+D(k−1)[k][j]\text{weight} = D^{(k-1)}[i][k] + D^{(k-1)}[k][j]

    If it passes through kk, it does so once; splitting it there leaves two paths with intermediate vertices in {1,…,k−1}\{1, \dots, k - 1\}:

  3. D(k)[i][j]=min⁡(D(k−1)[i][j], D(k−1)[i][k]+D(k−1)[k][j])D^{(k)}[i][j] = \min\big(D^{(k-1)}[i][j],\ D^{(k-1)}[i][k] + D^{(k-1)}[k][j]\big)

    Both candidates are weights of real walks from ii to jj through {1,…,k}\{1, \dots, k\}, and without negative cycles no walk beats the best simple path. So the minimum of the two is exact:

  4. D[i][k]←min⁡(D[i][k], D[i][k]+D[k][k])=D[i][k]D[i][k] \leftarrow \min\big(D[i][k],\ D[i][k] + D[k][k]\big) = D[i][k]

    One matrix suffices. During round kk, row kk and column kk keep their values, because D[k][k]=0D[k][k] = 0. So overwriting entries in place reads exactly what the two-matrix version reads:

Negative cycles. If a negative cycle passes through ii, the recurrence eventually finds it as a path from ii back to ii, and D[i][i]D[i][i] ends negative; pairs connected through such a cycle have no shortest path. The in-place argument then fails as well, since D[k][k]<0D[k][k] < 0 is possible, and entries can grow very negative, so with fixed-width integers stop as soon as a diagonal entry turns negative. Replacing (min⁡,+)(\min, +) by (or, and) gives Warshall's transitive closure, which runs in O(n3/w)O(n^3 / w) with ww-bit words using bitsets.

Check your understanding

In Floyd–Warshall, what does D(2)[i][j]D^{(2)}[i][j] hold?

  1. The weight of a shortest path from ii to jj with at most 2 edges
  2. The weight of a shortest path from ii to jj that passes through vertex 2
  3. The weight of the second-shortest path from ii to jj
  4. The weight of a shortest path from ii to jj whose intermediate vertices are among vertices 1 and 2
Show the answer

D. The weight of a shortest path from ii to jj whose intermediate vertices are among vertices 1 and 2

Floyd–Warshall's index restricts which vertices may be used in between, not how many edges a path has. A path counted in D(2)[i][j]D^{(2)}[i][j] may use vertex 1, vertex 2, both or neither, and it has at most 3 edges.

Min-plus products

DerivationShortest paths as matrix powers
  1. W⋆ℓ[i][j]=min⁡{ w(P):P goes from i to j with at most ℓ edges }W^{\star \ell}[i][j] = \min\{\, w(P) : P \text{ goes from } i \text{ to } j \text{ with at most } \ell \text{ edges} \,\}

    By induction on ℓ\ell, the ℓ\ell-th min-plus power of WW holds the best paths with at most ℓ\ell edges (the zeros on the diagonal let a path "wait"):

  2. δ=W⋆(n−1)=W⋆2tfor any 2t≥n−1\delta = W^{\star (n-1)} = W^{\star 2^{t}} \quad \text{for any } 2^{t} \ge n - 1

    Without negative cycles, shortest paths have at most n−1n - 1 edges, and ⋆\star is associative, so repeated squaring reaches them:

  3. O(n3log⁡n)O(n^3 \log n)

    Each product costs O(n3)O(n^3) naively, and ⌈log⁡2(n−1)⌉\lceil \log_2(n - 1) \rceil squarings suffice:

Predict before you look

How many min-plus squarings W→W⋆2→W⋆4→⋯W \to W^{\star 2} \to W^{\star 4} \to \cdots does a graph with 1,0001{,}000 vertices need, at least, to be sure of having every shortest path?

Show the answer

10

Shortest paths have at most 999999 edges, and tt squarings cover paths of up to 2t2^t edges: 29=5122^9 = 512 is too few and 210=10242^{10} = 1024 is enough. Ten products of 10910^9 steps each is worse than Floyd–Warshall's single 10910^9, but it reduces APSP to matrix products, which is the point.

Conversely, one min-plus product is an all-pairs problem: put the rows ii, the middle indices kk and the columns jj in three layers, with edges i→ki \to k of weight A[i][k]A[i][k] and k→jk \to j of weight B[k][j]B[k][j]. The distance from ii to jj is then (A⋆B)[i][j](A \star B)[i][j]. So APSP and the min-plus product have the same complexity up to a logarithmic factor: an algorithm for either one is an algorithm for both.

Seidel: unweighted graphs at matrix-multiplication speed

For connected, undirected graphs without weights, Seidel (1995) computes all distances with O(log⁡n)O(\log n) integer matrix products, in O(nωlog⁡n)O(n^{\omega}\log n) time. The idea: square the graph, solve the squared graph recursively, and recover each distance from half of it.

DerivationSeidel’s recursion
  1. T[i][j]=δG2(i,j)=⌈D[i][j]/2⌉T[i][j] = \delta_{G^2}(i, j) = \big\lceil D[i][j] / 2 \big\rceil

    Square the graph. G2G^2 joins i≠ji \ne j whenever their distance in GG is at most 2, so its adjacency matrix comes from one product A⋅AA \cdot A. Distances halve, rounded up:

  2. O(log⁡n) levels, two products eachO(\log n) \text{ levels, two products each}

    Recurse. The diameter halves at every level, so after at most ⌈log⁡2n⌉\lceil \log_2 n \rceil levels the graph is complete and every distance is 1:

  3. D[i][j] is odd  ⟺  ∑k∈N(j)T[i][k]<deg⁡(j) T[i][j]D[i][j] \text{ is odd} \iff \sum_{k \in N(j)} T[i][k] < \deg(j)\, T[i][j]

    Recover the parity. D[i][j]D[i][j] is 2T[i][j]2T[i][j] or 2T[i][j]−12T[i][j] - 1. Every neighbor kk of jj has D[i][k]∈{D[i][j]−1,D[i][j],D[i][j]+1}D[i][k] \in \{D[i][j] - 1, D[i][j], D[i][j] + 1\}, and the neighbor before jj on a shortest path has D[i][j]−1D[i][j] - 1. If D[i][j]D[i][j] is even, every neighbor has T[i][k]≥T[i][j]T[i][k] \ge T[i][j]; if it is odd, every neighbor has T[i][k]≤T[i][j]T[i][k] \le T[i][j] and that one has T[i][j]−1T[i][j] - 1. So

  4. D[i][j]=2 T[i][j]−[ X[i][j]<deg⁡(j) T[i][j] ]D[i][j] = 2\,T[i][j] - \big[\, X[i][j] < \deg(j)\, T[i][j] \,\big]

    The sums for all pairs form one integer product X=T⋅AX = T \cdot A, so each level costs O(nω)O(n^{\omega}):

python
def seidel(A):
    """Distances of a connected, undirected, unweighted graph; A is its 0/1 adjacency matrix."""
    n = len(A)
    if all(A[i][j] or i == j for i in range(n) for j in range(n)):
        return [[0 if i == j else 1 for j in range(n)] for i in range(n)]   # complete graph
    A2 = matmul(A, A)
    B = [[1 if i != j and (A[i][j] or A2[i][j]) else 0 for j in range(n)] for i in range(n)]
    T = seidel(B)                        # distances in G^2: T = ceil(D / 2)
    X = matmul(T, A)                     # X[i][j] = sum of T[i][k] over the neighbors k of j
    deg = [sum(row) for row in A]
    return [[2 * T[i][j] - (X[i][j] < T[i][j] * deg[j]) for j in range(n)] for i in range(n)]

def matmul(P, Q):                        # stand-in for a fast O(n^omega) multiplication
    n = len(P)
    return [[sum(P[i][k] * Q[k][j] for k in range(n)) for j in range(n)] for i in range(n)]

With this naive matmul the cost is O(n3log⁡n)O(n^3\log n); the point is that any fast multiplication can be plugged in. Seidel's algorithm returns distances only: recovering the paths needs a "witness" kk for each entry of the products, which randomized techniques find with only polylogarithmic overhead.

The APSP conjecture

Fredman (1976) showed that APSP has decision trees of depth only O(n2.5)O(n^{2.5}), so cubic lower bounds cannot be proved by counting comparisons, and he turned this into an algorithm slightly faster than n3n^3, by a factor of about (log⁡n/log⁡log⁡n)1/3(\log n / \log\log n)^{1/3}. A long series of papers shaved further logarithmic factors. Williams (STOC 2014) then found a randomized algorithm running in n3/2Ω(log⁡n)n^3 / 2^{\Omega(\sqrt{\log n})} time, faster than n3/log⁡cnn^3 / \log^c n for every constant cc, by representing the min-plus product with low-degree polynomials borrowed from circuit complexity; Chan and Williams (SODA 2016) made it deterministic.

DerivationThe easy directions, and the surprise
  1. (A⋆B)[i][j]=δ(i,j) in the layered graph I→K→J(A \star B)[i][j] = \delta(i, j) \text{ in the layered graph } I \to K \to J

    A min-plus product is an APSP instance on the three-layer graph, so a fast APSP algorithm multiplies fast:

  2. ∃ i,j,k: w(i,k)+w(k,j)+w(j,i)<0  ⟺  min⁡i,j((W⋆W)[i][j]+w(j,i))<0\exists\, i, j, k:\ w(i, k) + w(k, j) + w(j, i) < 0 \iff \min_{i, j}\big((W \star W)[i][j] + w(j, i)\big) < 0

    One min-plus product finds a negative triangle:

  3. negative triangle in O(n3−ε)  ⟹  APSP in O(n3−ε′) for some ε′>0\text{negative triangle in } O(n^{3-\varepsilon}) \;\Longrightarrow\; \text{APSP in } O(n^{3-\varepsilon'}) \text{ for some } \varepsilon' > 0

    The surprise is the converse: a truly subcubic algorithm for negative triangle, which answers a single yes-or-no question, would give truly subcubic min-plus products and APSP.

This is how fine-grained complexity works: it cannot prove that APSP needs cubic time, but it ties many problems to a few conjectures, so that a lower bound for one is a lower bound for all, and an algorithm for one is an algorithm for all. The lesson Fine-Grained Complexity develops the framework, alongside SETH and 3SUM.

Key takeaways

  • Floyd–Warshall: D(k)D^{(k)} holds the best paths with intermediate vertices in {1,…,k}\{1, \dots, k\}; the kk loop is outermost, one matrix suffices because row and column kk stay fixed in round kk, and a negative diagonal entry reveals a negative cycle.
  • APSP is the min-plus power W⋆(n−1)W^{\star(n-1)}, reached by O(log⁡n)O(\log n) squarings, and one min-plus product is an APSP instance; fast matrix multiplication does not apply directly because min⁡\min has no inverse, though small integer weights can be encoded.
  • Seidel's algorithm solves unweighted undirected APSP in O(nωlog⁡n)O(n^{\omega}\log n): recurse on G2G^2, whose distances are ⌈D/2⌉\lceil D/2 \rceil, then fix each parity with one integer product.
  • The APSP conjecture says no O(n3−ε)O(n^{3-\varepsilon}) algorithm exists; the best known is n3/2Ω(log⁡n)n^3/2^{\Omega(\sqrt{\log n})} (Williams, 2014), and negative triangle, min-plus product and metricity checking are subcubic-equivalent to APSP (Vassilevska Williams & Williams).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In Seidel's algorithm, the distance between ii and jj in the squared graph G2G^2 is T[i][j]=3T[i][j] = 3. What can their distance D[i][j]D[i][j] in GG be?

  1. 5 or 6
  2. 6 only
  3. 3 or 4
  4. 1 or 2
Show the answer

A. 5 or 6

T=⌈D/2⌉T = \lceil D/2 \rceil, so D∈{5,6}D \in \{5, 6\}. The algorithm decides between them with the neighbors of jj: if ∑k∈N(j)T[i][k]<deg⁡(j) T[i][j]\sum_{k \in N(j)} T[i][k] < \deg(j)\,T[i][j], the distance is odd, so D=5D = 5; otherwise D=6D = 6.

Question 2

Repeated min-plus squaring costs O(n3log⁡n)O(n^3\log n), more than Floyd–Warshall. Why does it matter anyway?

  1. It is faster in practice because of better cache behavior
  2. It can handle negative cycles, which Floyd–Warshall cannot
  3. It reduces APSP to O(log⁡n)O(\log n) min-plus products, so any faster product algorithm, such as Williams's, immediately speeds up APSP
  4. It needs asymptotically less memory
Show the answer

C. It reduces APSP to O(log⁡n)O(\log n) min-plus products, so any faster product algorithm, such as Williams's, immediately speeds up APSP

Repeated squaring makes the min-plus product the core of APSP, and the three-layer construction shows the converse. Faster products, such as Williams's n3/2Ω(log⁡n)n^3/2^{\Omega(\sqrt{\log n})} algorithm, therefore transfer directly to all-pairs shortest paths.

Question 3

Why can't Strassen-style fast matrix multiplication compute min-plus products directly?

  1. Because the min-plus product is not associative
  2. Because (min⁡,+)(\min, +) has no subtraction, and fast matrix multiplication relies on cancelling terms
  3. Because min-plus matrices are never square
  4. Because fast matrix multiplication only works modulo 2
Show the answer

B. Because (min⁡,+)(\min, +) has no subtraction, and fast matrix multiplication relies on cancelling terms

Strassen's seven products combine terms that are later subtracted away; with min⁡\min there is no way to undo a combination. For small integer weights, encoding entries as powers of xx restores a ring and gives O~(Mnω)\tilde O(M n^{\omega}), but for general weights no such trick is known.

Question 4

Which statement about the APSP conjecture is correct, as of 2025?

  1. It has been proved, in the decision-tree model
  2. Williams's 2014 algorithm refuted it
  3. It states that APSP requires Ω(n3)\Omega(n^3) time on the word RAM
  4. It says no algorithm runs in O(n3−ε)O(n^{3-\varepsilon}) for any ε>0\varepsilon > 0, which is consistent with Williams's n3/2Ω(log⁡n)n^3/2^{\Omega(\sqrt{\log n})} algorithm
Show the answer

D. It says no algorithm runs in O(n3−ε)O(n^{3-\varepsilon}) for any ε>0\varepsilon > 0, which is consistent with Williams's n3/2Ω(log⁡n)n^3/2^{\Omega(\sqrt{\log n})} algorithm

Williams's algorithm beats n3/log⁡cnn^3/\log^c n for every constant cc, but 2Ω(log⁡n)2^{\Omega(\sqrt{\log n})} grows more slowly than any nεn^{\varepsilon}, so the conjecture survives. It remains unproven.

Further reading

  • R. W. Floyd, "Algorithm 97: Shortest path," Communications of the ACM 5(6) (1962), 345.
  • M. L. Fredman, "New bounds on the complexity of the shortest path problem," SIAM Journal on Computing 5(1) (1976), 83–89.
  • R. Seidel, "On the all-pairs-shortest-path problem in unweighted undirected graphs," Journal of Computer and System Sciences 51(3) (1995), 400–403.
  • R. Williams, "Faster all-pairs shortest paths via circuit complexity," STOC (2014), 664–673.
  • V. Vassilevska Williams & R. Williams, "Subcubic equivalences between path, matrix, and triangle problems," Journal of the ACM 65(5) (2018), article 27; preliminary version at FOCS 2010.