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:

  1. Find shortest distances between all pairs of vertices
  2. 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
INPUT GRAPHALGORITHMRESULT01234231Adjacency Matrix[0, 4, 2, ∞][∞, 0, ∞, 3][∞, ∞, 0, 1]Find: 0 → 31Initialize Matricesdist[i][j] = graph[i][j]next[i][j] = j if edge exists2Triple Nested LoopFor k=0 to n-1: if dist[i][k]+dist[k][j] < dist[i][j]: update dist[i][j] & next[i][j]3Reconstruct PathFollow next[start][end] chainuntil reaching destinationTime: O(n³), Space: O(n²)023Shortest Path[0, 2, 3]Distance: 3Path via node 2 is optimalKey Insight:Floyd-Warshall considers each vertex as a potential shortcut between every pair,systematically building the optimal distance matrix in O(n³) time.TutorialsPoint - Floyd-Warshall All Pairs | Dynamic Programming
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen