AlgoPlusAlgoPlus
Learn/Data Structures & Algorithms
Lesson

Floyd-Warshall

All-pairs shortest paths by switching on one 'layover' vertex at a time and re-checking every pair against it.

9 min read Watch it move Build it

Floyd-Warshall answers a bigger question than Dijkstra or Bellman-Ford: not just the shortest path from *one* source, but the shortest distance between every pair of vertices, all at once. It does it with a strikingly simple idea — let one vertex at a time act as a permitted layover, and re-check every route against it.

The distance matrix and the layover

Keep a grid dist[i][j] — the best-known distance from i to j, starting as the direct edge weight (or if there's no edge, 0 on the diagonal). Now consider each vertex k in turn as an allowed intermediate stop. For *every* pair (i, j), ask: is going i → k → j cheaper than the best i → j found so far? After every vertex has had its turn as k, the grid holds all true shortest distances.

function floydWarshall(dist) {  // dist[i][j] preloaded with edge weights
  const n = dist.length;
  for (let k = 0; k < n; k++)          // each vertex as a layover
    for (let i = 0; i < n; i++)        // every source
      for (let j = 0; j < n; j++)      // every destination
        if (dist[i][k] + dist[k][j] < dist[i][j])
          dist[i][j] = dist[i][k] + dist[k][j];  // route through k
  return dist;
}
The k loop must be outermost
The order is non-negotiable: k (the layover) wraps the i and j loops. Each k round may only build on distances already allowing layovers 0..k−1. Swap the loops and you'd consider a shortcut through k before k's own best paths were known — and get wrong answers.
Three loops, no priority queue
Floyd-Warshall is just three nested loops and a comparison — no heap, no edge sorting. That bluntness makes it ideal for dense graphs and small-to-medium vertex counts, where its simplicity beats running a single-source algorithm from every vertex.
OperationTimeSpace
All-pairs shortest paths · three nested loops over the distance matrixO(V³)O(V²)
Check yourself
In Floyd-Warshall, what does each iteration of the outer k loop do?