How Floyd-Warshall closes all-pairs distances

Short answer: Floyd-Warshall computes the shortest path between every pair by allowing intermediate vertices in order. After step k, dist[i][j] is the best path that uses only intermediates among the first k vertices. The triple loop is Θ(V³) time and Θ(V²) memory. Negative edges are allowed. A negative value on the diagonal after the loops is a negative cycle.


What the problem actually asks

All-pairs distances can be V single-source runs. That is the right reduction when a heap-based Dijkstra is cheap and weights are nonnegative. A dense graph, or a graph with negative edges and no negative cycle, wants a single cubic pass that does not depend on a heap. The inductive object is a path whose intermediate vertices are restricted to a prefix of the vertex list.

A path that is allowed to use vertex k either avoids k, in which case the previous matrix already has it, or it goes from i to k and from k to j using only lower intermediates. Those two pieces are independent once k is the highest intermediate, which is why one matrix, updated in place, is enough if k is the outer index.


What the algorithm guarantees

Initialized with edge weights, zeros on the diagonal, and infinity elsewhere, the algorithm returns true shortest-path distances whenever no negative cycle exists. Time is Θ(V³) regardless of how many edges exist, so a sparse graph with nonnegative weights is usually faster as V runs of Dijkstra. Extra memory is the distance matrix. A predecessor matrix, updated whenever dist[i][k]+dist[k][j] wins, reconstructs one path.

In-place update is correct when the k loop is outermost. Then the values read for intermediate k were finalized at this k or earlier, and a path does not need k twice unless a negative cycle is present. After termination, dist[v][v] < 0 means a negative cycle through v. The algorithm has no separate detection pass.


The working steps

  1. Number vertices 0..n−1. Set dist[i][i] = 0, dist[i][j] to the weight of edge i→j when it exists, and infinity otherwise. Keep the best edge if parallel edges exist.
  2. For k from 0 to n−1, for every pair i, j, if dist[i][k] + dist[k][j] < dist[i][j], replace dist[i][j] and optionally set pred[i][j] = pred[k][j].
  3. Add two infinities as infinity, so a missing intermediate does not look like a path.
  4. After the loops, any negative dist[v][v] is a negative cycle. Path reconstruction through that pair is undefined.
  5. Read dist[i][j] as the shortest-path distance. Walk predecessors from j back toward i to recover a path when no negative cycle exists.

The cubic bound counts triples, not edges. A sparse nonnegative instance belongs to repeated Dijkstra, and a sparse instance with negative edges belongs to Johnson, which reweights and then runs Dijkstra. Floyd-Warshall is the dense, simple all-pairs algorithm, including the negative-cycle test on the diagonal.


Approaches that look simpler and fail

Approach Why it fails when the k loop is not outermost
Loop i or j outside k and update one matrix A value may then use vertex k more than once inside a single pair’s update, or miss the inductive order. The proof is the outer k.
V runs of Dijkstra while a negative edge exists Dijkstra’s settled distances are unsafe. The cubic algorithm does not settle a vertex early.
Treat a negative diagonal as a usable distance A negative cycle makes that pair’s distance unbounded below. The number in the matrix is an artifact of n passes, not a shortest path.
Use Θ(V³) as a reason to prefer it on a sparse road network Repeated Dijkstra or Johnson tracks E. The triple loop always pays n³.

Sparse nonnegative all-pairs distances belong to a Dijkstra run from each vertex. Sparse all-pairs with negative edges and no desire to pay n³ belong to Johnson’s reweighting.


A working example

The Bash script and the Python script run Floyd–Warshall with k as the outermost index. A missing edge is 999. Both print the distance matrix from vertex 0, then 1, then 2: 0 1 3 / 999 0 2 / 999 999 0.

INF=999
# row-major, 3 vertices, edges 0->1 weight 1 and 1->2 weight 2
d=(0 1 999  999 0 2  999 999 0)
n=3
at() { echo "${d[$(( $1 * n + $2 ))]}"; }
for ((k=0; k<n; k++)); do
  for ((i=0; i<n; i++)); do
    for ((j=0; j<n; j++)); do
      ik=$(at $i $k); kj=$(at $k $j); ij=$(at $i $j)
      if (( ik + kj < ij )); then d[i*n+j]=$((ik+kj)); fi
    done
  done
done
echo "${d[0]} ${d[1]} ${d[2]}"
echo "${d[3]} ${d[4]} ${d[5]}"
echo "${d[6]} ${d[7]} ${d[8]}"
INF = 999
d = [
    [0, 1, INF],
    [INF, 0, 2],
    [INF, INF, 0],
]
n = 3
for k in range(n):
    for i in range(n):
        for j in range(n):
            if d[i][k] + d[k][j] < d[i][j]:
                d[i][j] = d[i][k] + d[k][j]
assert d == [[0, 1, 3], [999, 0, 2], [999, 999, 0]]
for row in d:
    print(*row)

Where it is used

Floyd-Warshall fills the all-pairs distance matrix of a small network, and the same triple loop computes a transitive closure if the operation is Boolean. A campus map or a dense tariff table is the right size. A sparse road graph uses Johnson or repeated Dijkstra.


When you can drop this algorithm

Drop Floyd-Warshall on a large sparse graph. Keep it for dense graphs, for a short implementation of all-pairs distances, and for a negative-cycle test that falls out of the same matrix.


Why this stays published

We publish this so a search for Floyd-Warshall returns the outer intermediate index and the negative diagonal that reports a cycle. Floyd-Warshall computes all-pairs distances in Θ(V³) time by adding one allowed intermediate at a time, and a negative diagonal is a negative cycle.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *