AlgoFrames

Floyd-Warshall: all pairs

Floyd-Warshall finds shortest paths between every pair of vertices. The distance matrix updates once for each vertex allowed as a midpoint.

Before you start: 0-1 BFS and multi-source BFS.

The idea

A road atlas prints one table with the distance between every pair of cities. Floyd-Warshall builds that table for any graph.

Running a single-source search from every vertex also works. Floyd-Warshall is shorter to write and handles negative edges.

Intuition

Allow one vertex k as a midpoint. The route i → k → j costs dist[i][k] + dist[k][j], and it wins when that beats dist[i][j].

Allow the midpoints one at a time: 0, then 1, and so on. After vertex k, each cell holds the best route through midpoints 0 to k.

A best route through midpoints 0 to k either skips k or passes it once. The two halves only use midpoints 0 to k − 1, which are already final.

Complexity

Three nested loops each run V times, so the time is O(V³). The work does not depend on the number of edges.

On sparse graphs, Dijkstra from every vertex is faster. On dense graphs or with negative edges, Floyd-Warshall is the simple choice.

The matrix has V × V cells, so space is O(V²). Each round k updates the same matrix in place.

Pitfalls

Keep k as the outer loop. With k inside, cell (0, 1) stays ∞, yet 0 → 3 → 2 → 1 costs 3.

Round k needs row k and column k to be final for midpoints below k. Only the outer k loop guarantees that.

A negative cycle shows up on the diagonal as a cell (v, v) below 0. Then the other cells are no longer true distances.

Variations

Swap + for AND and min for OR, and the same loops answer whether row can reach column. This is transitive closure of the graph shown.

Code

Pseudocode

dist ← n × n matrix of ∞, dist[i][i] ← 0
for each edge (u, v, w): dist[u][v] ← w
for k in 0 … n − 1
  for i in 0 … n − 1
    for j in 0 … n − 1
      if dist[i][k] + dist[k][j] < dist[i][j]
        dist[i][j] ← dist[i][k] + dist[k][j]
return dist  (a negative dist[i][i] means a negative cycle)

Python

def floyd_warshall(n, edges):
    INF = float("inf")
    dist = [[0 if i == j else INF for j in range(n)] for i in range(n)]
    for u, v, w in edges:
        dist[u][v] = min(dist[u][v], w)
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if dist[i][k] + dist[k][j] < dist[i][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]
    return dist

JavaScript

function floydWarshall(n, edges) {
  const dist = Array.from({ length: n }, (_, i) =>
    Array.from({ length: n }, (_, j) => (i === j ? 0 : Infinity)));
  for (const [u, v, w] of edges) dist[u][v] = Math.min(dist[u][v], w);
  for (let k = 0; k < n; k++) {
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < n; j++) {
        if (dist[i][k] + dist[k][j] < dist[i][j]) {
          dist[i][j] = dist[i][k] + dist[k][j];
        }
      }
    }
  }
  return dist;
}

Cost at a glance

TimeO(V³)
SpaceO(V²)
InputNo negative cycles
OutputShortest distances between all pairs

Practice problems (4)

Matrix after k = 1 Warm-up

The vertices are numbered 1 to 4. Floyd-Warshall first allows vertex 1 as a midpoint. Predict how the matrix changes in that round.

Implement Floyd-Warshall Standard

A directed graph has n vertices and edges, where edges[i] = [from, to, weight]. Return an n × n matrix dist, where dist[i][j] is the shortest distance from i to j, or -1 when j cannot be reached.

Weights are non-negative. Two edges may join the same pair.

City with the fewest reachable neighbors Standard

There are n cities and two-way roads edges, where edges[i] = [a, b, length]. A city reaches another when the shortest road distance between them is at most distanceThreshold.

Return the city that reaches the fewest other cities. On a tie, return the largest city number.

Which loop goes outside? Standard

A student writes Floyd-Warshall with the loops in the order i, j, k, so k is the innermost loop. On the chain shown, one cell comes out wrong. Why?

Related topics

Next on the path: A* search with heuristics