Algorithms · Floyd-Warshall, Transitive Closure, Johnson and Multistage Graphs
The All-Pairs Shortest Path (APSP) Problem
This chapter is the "all-pairs" chapter. It collects the four tools GATE keeps returning to: Floyd-Warshall (all-pairs shortest paths with negative edges), Warshall (transitive closure), Johnson (all-pairs when the graph is sparse and has negative edges), and the multistage graph (a DAG shortest/longest path by stages). We build each from zero, trace every matrix by hand, and finish with the exam patterns and traps.
Input: a directed graph with weight function (weights may be negative; no negative cycle reachable, or we must detect one). Output: a matrix where is the minimum weight of any path from to .
Notation used throughout:
| Symbol | Meaning |
|---|---|
| or | number of vertices |
| number of edges | |
| shortest path using only intermediate vertices from | |
| direct edge weight; if no edge; if | |
| the whole matrix after stage |
Convention note (important for GATE): vertices are usually numbered (1-based) in Floyd-Warshall traces, and the "allowed intermediate set" after stage is . Some books (and code) use ; then stage allows . The recurrence is identical — only the index range shifts. GATE traces almost always use 1-based vertices and ask for after a named .
Floyd-Warshall: The Recurrence
The key idea: a shortest path from to either does not use vertex as an intermediate, or does, in which case it splits at :
with base case
Why it is correct: any shortest path's intermediate vertices form a subset of ; we add them one at a time. At stage we have "permission" to route through , and the two sub-paths and use only — exactly what stores. This is optimal substructure, so DP applies.
Complexity: three nested loops over → time. The matrix is → space. (We update in place; the -th row and column are unchanged by stage , so in-place is safe.)
Algorithm (1-based):
for i = 1..n: for j = 1..n: D[i][j] = (i==j) ? 0 : w(i,j) or INF
for k = 1..n:
for i = 1..n:
for j = 1..n:
if D[i][k] + D[k][j] < D[i][j]:
D[i][j] = D[i][k] + D[k][j]