Floyd-Warshall Algorithm

medium

Given a directed graph with V vertices (0 .. V-1) and edges edges[i] = [u, v, w] with non-negative weight w, return the all-pairs shortest distance matrix D, where D[i][j] is the shortest distance from i to j (0 when i == j, -1 if j is unreachable from i).

Hints

You need every pair's distance, so think all-pairs, not single-source.
For each intermediate vertex k, check if routing i→k→j is shorter.
Three nested loops with k outermost: D[i][j] = min(D[i][j], D[i][k] + D[k][j]).

Common doubts

The invariant is 'shortest paths using intermediates 0..k'; you must fully incorporate each k before moving on, which requires k outside i and j.
On dense graphs (E ≈ V²) it's simpler and comparable, and it handles negative edges, which Dijkstra can't.
If any diagonal entry D[i][i] becomes negative, i lies on a negative cycle.

Interview follow-ups

Keep a 'next' (or 'via') matrix updated whenever you relax, then trace it.
Seed both D[u][v] and D[v][u] from each edge.

Fun facts

  • Floyd-Warshall is dynamic programming over the set of allowed intermediate vertices.
  • Its transitive-closure cousin (replace min/+ with OR/AND) computes reachability.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: V = 3, edges = [[0,1,3],[1,2,1],[0,2,10]]
Output: [[0,3,4],[-1,0,1],[-1,-1,0]]
0→1→2 (4) beats the direct 0→2 (10); rows 1 and 2 can't reach earlier vertices.
Example 2
Input: V = 2, edges = [[0,1,5]]
Output: [[0,5],[-1,0]]
Only 0→1 exists; 1 can't reach 0.
Constraints

- 1 <= V <= 100 - 0 <= edges.length <= V*(V-1) - 1 <= w <= 10^4 - edges are directed

Solve this problem →