Floyd-Warshall All Pairs - Problem
The Floyd-Warshall algorithm is a fundamental dynamic programming approach for finding shortest paths between all pairs of vertices in a weighted graph. Unlike Dijkstra's algorithm which finds shortest paths from a single source, Floyd-Warshall computes the shortest distance between every pair of vertices in one execution.
Given a weighted directed graph represented as an adjacency matrix, implement the Floyd-Warshall algorithm to:
- Find shortest distances between all pairs of vertices
- Reconstruct the actual path between any two specified nodes
The graph may contain negative edge weights, but no negative cycles. Use infinity to represent no direct edge between vertices.
Input & Output
Example 1 — Basic 4-Node Graph
$
Input:
graph = [[0,4,2,1000000],[1000000,0,1000000,3],[1000000,1000000,0,1],[1000000,1000000,1000000,0]], start = 0, end = 3
›
Output:
[0,2,3]
💡 Note:
Direct path 0→3 doesn't exist (cost 1000000). Path 0→2→3 has cost 2+1=3, which is shorter than 0→1→3 (cost 4+3=7). Floyd-Warshall finds this optimal route.
Example 2 — Direct Path Available
$
Input:
graph = [[0,5,1000000,10],[1000000,0,3,1000000],[1000000,1000000,0,1],[1000000,1000000,1000000,0]], start = 0, end = 1
›
Output:
[0,1]
💡 Note:
Direct path 0→1 with cost 5 exists and is optimal. No intermediate path through other vertices provides improvement.
Example 3 — No Path Exists
$
Input:
graph = [[0,1000000,1000000,1000000],[1000000,0,2,1000000],[1000000,1000000,0,1000000],[1000000,1000000,1000000,0]], start = 0, end = 3
›
Output:
[]
💡 Note:
Node 0 is disconnected from node 3. No path exists between them, so return empty array.
Constraints
- 1 ≤ n ≤ 100 (where n is number of vertices)
- -1000 ≤ graph[i][j] ≤ 1000 for valid edges
- graph[i][j] = 1000000 represents no edge (infinity)
- 0 ≤ start, end < n
- No negative cycles in the graph
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code