Implement Floyd-Warshall
Standard · Write code · about 12 min
A directed graph has n vertices and edges, where edges[i] = [from, to, weight]. Return an n × n matrix dist, where dist[i][j] is the shortest distance from i to j, or -1 when j cannot be reached.
Weights are non-negative. Two edges may join the same pair.
Example 1
Input:
[4,[[0,1,3],[1,2,1],[2,3,2],[0,3,9],[3,0,1]]]
Output:
[[0,3,4,6],[4,0,1,3],[3,6,0,2],[1,4,5,0]]
Row 2: 2 → 3 → 0 costs 3 and 2 → 3 → 0 → 1 costs 6.
Example 2
Input:
[3,[[0,1,4],[1,2,1],[0,2,7],[2,0,2]]]
Output:
[[0,4,5],[3,0,1],[2,6,0]]
Constraints
- 1 ≤ n ≤ 100
- 0 ≤ edges.length ≤ 1,000
- 0 ≤ weight ≤ 100
Learn the idea first: Floyd-Warshall: all pairs, a visual lesson.
More Floyd-Warshall: all pairs problems
- Matrix after k = 1 Warm-up
- City with the fewest reachable neighbors Standard
- Which loop goes outside? Standard