Skip to problem
←

Floyd–Warshall: All-Pairs Shortest Paths

Medium 0 attempts

You're given a directed, weighted graph as a V x V adjacency matrix graph, where graph[i][j] holds the weight of the edge going from vertex i to vertex j, and every diagonal entry graph[i][i] is 0. Compute the shortest distance between every pair of vertices using the Floyd-Warshall all-pairs shortest path algorithm. Wherever no path connects two vertices, leave the distance at the large sentinel value 10000, which stands in for infinity.

Function contract

graph is a square directed adjacency matrix. Diagonal entries are 0; 10000 means no direct edge. Negative edge weights are allowed, but negative cycles are not.

Output: Return the shortest-distance matrix. Use 10000 for unreachable pairs; reachable distances are not capped at 10000.

Example 1

Input
graph = [[0,3,10000,5],[2,0,10000,4],[10000,1,0,10000],[10000,10000,2,0]]
Output
[[0,3,7,5],[2,0,6,4],[3,1,0,5],[5,3,2,0]]

Example 2

Input
graph = [[0,10000],[10000,0]]
Output
[[0,10000],[10000,0]]

Example 3

Input
graph = [[0,10000,10000],[10000,0,-2],[10000,10000,0]]
Output
[[0,10000,10000],[10000,0,-2],[10000,10000,0]]
Constraints
  • 1 <= V <= 100
  • graph[i][i] == 0
  • 10000 denotes an absent edge; existing edge weights are integers in [-1000,1000].
  • There are no negative-weight cycles.

Approach: Floyd-Warshall

Convert absent edges to actual Infinity internally: the numeric sentinel must not participate in arithmetic, especially with negative edges, or cap long reachable paths. Convert only unreachable entries back to 10000 afterward.

Use three nested loops. For each intermediate vertex k, update the shortest path between every pair (i, j) by checking if going through k gives a shorter distance: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]).

javascript
function floydWarshall(graph) {
  const n = graph.length;
  const dist = graph.map(row => row.map(v => v === 10000 ? Infinity : v));
  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.map(row => row.map(v => v === Infinity ? 10000 : v));
}

Time Complexity: O(V³)

Space Complexity: O(V²)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript