Floyd–Warshall visualization

All-pairs shortest paths by allowing one more intermediate vertex k at a time.

D[i][j] holds the shortest i→j distance using only intermediate vertices from the first k. Adding vertex k as a possible stop: D[i][j] = min(D[i][j], D[i][k] + D[k][j]).

Works with negative edges. Edge case: a negative value on the diagonal D[i][i] < 0 at the end means vertex i lies on a negative cycle.

Complexity

Time: best O(V³), average O(V³), worst O(V³). Space: O(V²). Difficulty: Advanced.

Pseudocode

procedure floydWarshall(G):
  D[i][j] ← w(i, j); D[i][i] ← 0; otherwise ∞
  for k in V:
    for i in V:
      for j in V:
        if D[i][k] + D[k][j] < D[i][j]:
          D[i][j] ← D[i][k] + D[k][j]
  if any D[i][i] < 0: negative cycle

More graphs algorithms