1. Gyanastra
  2. Algorithms
  3. Floyd-Warshall, Transitive Closure, Johnson and Multistage Graphs
  4. The All-Pairs Shortest Path (APSP) Problem
Free lesson, no account needed 4 min read

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 G=(V,E)G=(V,E) with weight function w:E→Rw:E\to\mathbb{R} (weights may be negative; no negative cycle reachable, or we must detect one). Output: a V×VV\times V matrix DD where D[i][j]D[i][j] is the minimum weight of any path from ii to jj.

Notation used throughout:

SymbolMeaning
nn or VVnumber of vertices
EEnumber of edges
dij(k)d_{ij}^{(k)}shortest i→ji\to j path using only intermediate vertices from {1,…,k}\{1,\dots,k\}
w(i,j)w(i,j)direct edge weight; ∞\infty if no edge; 00 if i=ji=j
D(k)D^{(k)}the whole matrix after stage kk

Convention note (important for GATE): vertices are usually numbered 1…n1\dots n (1-based) in Floyd-Warshall traces, and the "allowed intermediate set" after stage kk is {1,…,k}\{1,\dots,k\}. Some books (and code) use 0…n−10\dots n-1; then stage kk allows {0,…,k}\{0,\dots,k\}. The recurrence is identical — only the index range shifts. GATE traces almost always use 1-based vertices and ask for D(k)D^{(k)} after a named kk.


Floyd-Warshall: The Recurrence

The key idea: a shortest path from ii to jj either does not use vertex kk as an intermediate, or does, in which case it splits at kk:

dij(k)=min⁡(dij(k−1),  dik(k−1)+dkj(k−1))d_{ij}^{(k)} = \min\Big(d_{ij}^{(k-1)},\; d_{ik}^{(k-1)} + d_{kj}^{(k-1)}\Big)

with base case

dij(0)={0i=jw(i,j)(i,j)∈E∞otherwised_{ij}^{(0)} = \begin{cases} 0 & i=j\\ w(i,j) & (i,j)\in E\\ \infty & \text{otherwise}\end{cases}

Why it is correct: any shortest path's intermediate vertices form a subset of {1,…,n}\{1,\dots,n\}; we add them one at a time. At stage kk we have "permission" to route through kk, and the two sub-paths i→ki\to k and k→jk\to j use only {1,…,k−1}\{1,\dots,k-1\} — exactly what D(k−1)D^{(k-1)} stores. This is optimal substructure, so DP applies.

Complexity: three nested loops over k,i,jk,i,j → O(V3)O(V^3) time. The matrix is V×VV\times V → O(V2)O(V^2) space. (We update in place; the kk-th row and column are unchanged by stage kk, 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]

Pages 1–2 of 2