Skip to content
StackDecode
GraphsAnimated

Floyd–Warshall Algorithm

Try every node as an intermediate stop for every pair.

Time

O(V³)

Extra space

O(V²)

Use it for

All-pairs shortest paths on small graphs.

How it works

  1. Build a table of the best known distance between every pair of nodes (direct edges only at first).
  2. For each node k in turn, ask for every pair (i, j): is going i → k → j shorter than the best route so far?
  3. After all nodes have been tried as the intermediate stop, the table holds all shortest distances.
  4. Three nested loops: O(V³). Handy for small graphs and when you need every pair.

Watch it run

Loading animation…