Floyd-Warshall
30 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Floyd-Warshall computes shortest paths between every pair of vertices in O(V^3) time using dynamic programming.
All-pairs shortest paths via dynamic programming
Many routing problems ask for shortest path distances between every pair of vertices. Running single-source Dijkstra from each vertex takes O(V * (V + E) log V) time. On dense graphs with negative edge weights, running Dijkstra repeatedly fails completely.
Example 1 · All-Pairs Shortest Paths with Negative Cycle Check
import java.util.Arrays;
public class FloydWarshallDemo { public static final int INF = 1_000_000_000;
public static int[][] floydWarshall(int n, int[][] edges) { int[][] dist = new int[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(dist[i], INF); dist[i][i] = 0; } for (int[] e : edges) { dist[e[0]][e[1]] = e[2]; }
for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dist[i][k] != INF && dist[k][j] != INF) { dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); } } } } return dist; }
public static void main(String[] args) { int n = 4; // edges: {u, v, weight} int[][] edges = { {0, 1, 5}, {0, 3, 10}, {1, 2, 3}, {2, 3, 1} }; int[][] dist = floydWarshall(n, edges); System.out.println("0 to 3 shortest: " + dist[0][3]); System.out.println("0 to 2 shortest: " + dist[0][2]); }}0 to 3 shortest: 9 0 to 2 shortest: 8
What this code does
- Initialises distance matrix with diagonal zeros and infinity for absent edges.
- Iterates intermediate vertex k in the outermost loop to guarantee bottom-up optimality.
- Improves path 0 to 3 from direct 10 down to 0->1->2->3 with total cost 9.
Floyd-Warshall solves all-pairs shortest paths in O(V^3) time with concise code. It maintains a 2D distance matrix dist[i][j] representing path costs. For every intermediate vertex k, it tests if routing through k improves the path. The core recurrence is dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]). Consider three vertices 0, 1, and 2. Initially, dist[0][2] is 9, direct edge 0->1 is 3, and edge 1->2 is 4. When vertex 1 is evaluated as the intermediate stepping stone, 3 + 4 equals 7. Since 7 is less than 9, dist[0][2] improves to 7.
The intermediate vertex order: why k must be the outer loop
The dynamic programming state dp[k][i][j] represents shortest paths using intermediate nodes up to k. Intermediate vertices are vertices strictly inside the path between endpoints i and j. Putting k in the innermost loop fails because paths using multiple hops are not yet known.
Example 2 · Shortest Path Reconstruction with Next Pointer Matrix
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class PathReconstructionFloydDemo { public static final int INF = 1_000_000_000;
public static void main(String[] args) { int n = 4; int[][] dist = new int[n][n]; int[][] next = new int[n][n]; for (int i = 0; i < n; i++) { Arrays.fill(dist[i], INF); Arrays.fill(next[i], -1); dist[i][i] = 0; } int[][] edges = {{0, 1, 3}, {1, 2, 2}, {2, 3, 4}, {0, 3, 15}}; for (int[] e : edges) { dist[e[0]][e[1]] = e[2]; next[e[0]][e[1]] = e[1]; }
for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; next[i][j] = next[i][k]; } } } }
List<Integer> path = new ArrayList<>(); int u = 0, v = 3; for (int curr = u; curr != -1; curr = next[curr][v]) { path.add(curr); if (curr == v) break; } System.out.println("Path 0 to 3: " + path); }}Path 0 to 3: [0, 1, 2, 3]
What this code does
- Maintains next[i][j] pointing to the immediate successor along shortest path from i to j.
- Updates next[i][j] to next[i][k] whenever detour through intermediate vertex k is strictly better.
- Reconstructs full path sequence [0, 1, 2, 3] by traversing next pointers.
The outer loop on k ensures that all shorter subpaths are already fully settled. Before testing detour k, paths from i to k and k to j only use nodes 0 through k - 1. This bottom-up dependency requires the loop order k, then i, then j. Negative cycles are also easy to spot in the distance matrix. If any diagonal entry dist[i][i] becomes negative, node i is inside a negative cycle. A vertex reaching itself with a cost less than zero indicates infinite cost reduction.
Find the bug
Spot the Floyd-Warshall bug
Select the line that is wrong.
Try vertex k as the stop between i and j.
Round 1 of 3Transitive closure and reachability matrix
Transitive closure answers reachability queries: can vertex i reach vertex j along directed edges. Warshall's algorithm computes reachability by replacing arithmetic with boolean logic. Instead of minimum and addition, use logical OR and logical AND operations.
Example 3 · Transitive Closure Reachability Matrix
public class TransitiveClosureDemo { public static boolean[][] transitiveClosure(int n, int[][] edges) { boolean[][] reach = new boolean[n][n]; for (int i = 0; i < n; i++) { reach[i][i] = true; } for (int[] e : edges) { reach[e[0]][e[1]] = true; }
for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]); } } } return reach; }
public static void main(String[] args) { int n = 4; int[][] edges = {{0, 1}, {1, 2}, {2, 3}}; boolean[][] reach = transitiveClosure(n, edges); System.out.println("0 reaches 3: " + reach[0][3]); System.out.println("3 reaches 0: " + reach[3][0]); }}0 reaches 3: true 3 reaches 0: false
What this code does
- Initialises reflexive diagonal reachability reach[i][i] = true.
- Propagates reachability if path i to k exists and path k to j exists.
- Correctly reports that node 0 can reach 3 via directed edges, but 3 cannot reach 0.
The recurrence becomes reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]). This boolean matrix identifies all connected component dependencies. Bitwise operations can accelerate transitive closure by packing 64 booleans per long. Floyd-Warshall is ideal when vertex count V is at most 400. At V = 400, cubic operations total 64 million, completing in under 0.1 seconds in Java. When V exceeds 1000, Floyd-Warshall is too slow and requires sparse graph alternatives.
Next step
Check your understanding
10 quick questions