1. Gyanastra
  2. Algorithms
  3. Floyd-Warshall, Transitive Closure, Johnson and Multistage Graphs
  4. Full Trace: 4-Vertex Graph
Free lesson, no account needed 13 min read

Algorithms · Floyd-Warshall, Transitive Closure, Johnson and Multistage Graphs

Full Trace: 4-Vertex Graph

Take this directed weighted graph (vertices 1–4):

   1 --3 2
   1 --8 4
   2 --1 3
   3 --2 4
   4 --5 1
   (all other pairs: no edge)

Base matrix D(0)D^{(0)} (rows = source, cols = destination; ∞\infty shown as ∞):

1234
103∞8
2∞01∞
3∞∞02
45∞∞0

Stage k=1k=1 (allow vertex 1 as intermediate)

Only paths that pass through 1 can improve. Check each i,ji,j where D[i][1]+  D[1][j]<D[i][j]D[i][1]+\;D[1][j] < D[i][j]:

  • D[4][1]=5D[4][1]=5; D[1][2]=3D[1][2]=3 → 5+3=85+3=8 vs D[4][2]=∞D[4][2]=\infty → update to 8.
  • D[4][1]=5D[4][1]=5; D[1][4]=8D[1][4]=8 → 5+8=135+8=13 vs D[4][4]=0D[4][4]=0 → no.
  • D[4][1]=5D[4][1]=5; D[1][3]=∞D[1][3]=\infty → ∞, no.
  • Rows 1,2,3 have D[i][1]=∞D[i][1]=\infty (except D[1][1]=0D[1][1]=0), so nothing else changes.

D(1)D^{(1)}:

1234
103∞8
2∞01∞
3∞∞02
458∞0

Stage k=2k=2 (allow vertices {1,2})

Column 2 entries: D[1][2]=3,  D[4][2]=8D[1][2]=3,\;D[4][2]=8; others ∞. Row 2: D[2][3]=1D[2][3]=1.

  • D[1][2]=3D[1][2]=3; D[2][3]=1D[2][3]=1 → 3+1=43+1=4 vs D[1][3]=∞D[1][3]=\infty → update to 4.
  • D[1][2]=3D[1][2]=3; D[2][4]=∞D[2][4]=\infty → no.
  • D[4][2]=8D[4][2]=8; D[2][3]=1D[2][3]=1 → 8+1=98+1=9 vs D[4][3]=∞D[4][3]=\infty → update to 9.
  • D[4][2]=8D[4][2]=8; D[2][4]=∞D[2][4]=\infty → no.

D(2)D^{(2)}:

1234
10348
2∞01∞
3∞∞02
45890

Stage k=3k=3 (allow {1,2,3})

Column 3: D[1][3]=4,  D[2][3]=1,  D[4][3]=9D[1][3]=4,\;D[2][3]=1,\;D[4][3]=9. Row 3: D[3][4]=2D[3][4]=2.

  • D[1][3]=4D[1][3]=4; D[3][4]=2D[3][4]=2 → 4+2=64+2=6 vs D[1][4]=8D[1][4]=8 → update to 6.
  • D[2][3]=1D[2][3]=1; D[3][4]=2D[3][4]=2 → 1+2=31+2=3 vs D[2][4]=∞D[2][4]=\infty → update to 3.
  • D[4][3]=9D[4][3]=9; D[3][4]=2D[3][4]=2 → 9+2=119+2=11 vs D[4][4]=0D[4][4]=0 → no.

D(3)D^{(3)}:

1234
10346
2∞013
3∞∞02
45890

Stage k=4k=4 (allow all vertices)

Column 4: D[1][4]=6,  D[2][4]=3,  D[3][4]=2D[1][4]=6,\;D[2][4]=3,\;D[3][4]=2. Row 4: D[4][1]=5D[4][1]=5.

  • D[1][4]=6D[1][4]=6; D[4][1]=5D[4][1]=5 → 6+5=116+5=11 vs D[1][1]=0D[1][1]=0 → no.
  • D[2][4]=3D[2][4]=3; D[4][1]=5D[4][1]=5 → 3+5=83+5=8 vs D[2][1]=∞D[2][1]=\infty → update to 8.
  • D[3][4]=2D[3][4]=2; D[4][1]=5D[4][1]=5 → 2+5=72+5=7 vs D[3][1]=∞D[3][1]=\infty → update to 7.
  • D[3][4]=2D[3][4]=2; D[4][2]=8D[4][2]=8 → 2+8=102+8=10 vs D[3][2]=∞D[3][2]=\infty → update to 10.
  • All other combinations through vertex 4 (e.g. D[1][4]+D[4][2]=6+8=14>3D[1][4]+D[4][2]=6+8=14>3, D[2][4]+D[4][3]=3+9=12>1D[2][4]+D[4][3]=3+9=12>1) give no improvement.

D(4)D^{(4)} (final):

1234
10346
28013
371002
45890

Sanity check: 2→12\to1 = 2→3→4→12\to3\to4\to1 = 1+2+5=81+2+5=8 ✓. 3→13\to1 = 3→4→13\to4\to1 = 2+5=72+5=7 ✓. 3→23\to2 = 3→4→1→23\to4\to1\to2 = 2+5+3=102+5+3=10 ✓. 1→41\to4 = 1→2→3→41\to2\to3\to4 = 3+1+2=63+1+2=6 ✓. The graph is strongly connected, so no entry is ∞\infty, matching the Warshall closure in §6.


Negative Cycle Detection

After the algorithm, if any diagonal entry D[i][i]<0D[i][i] < 0, there is a negative-weight cycle (through ii). Reason: a shortest path from ii to itself should be 0 (the empty path); a negative value means a cycle of negative total weight exists.

Trap: Floyd-Warshall still "works" with negative edges (unlike Dijkstra), but with a negative cycle the values are meaningless (they keep decreasing). So always check the diagonal at the end. Some implementations check during the run; checking once at the end is sufficient and standard.


Path Reconstruction with a Predecessor Matrix

Maintain Π[i][j]\Pi[i][j] = the predecessor of jj on the current best i→ji\to j path.

  • Init: Π[i][j]=i\Pi[i][j] = i if i≠ji\neq j and edge (i,j)(i,j) exists; else undefined (e.g. −1-1 or NIL).
  • Update: when D[i][k]+D[k][j]<D[i][j]D[i][k]+D[k][j] < D[i][j], set Π[i][j]=Π[k][j]\Pi[i][j] = \Pi[k][j] (the predecessor of jj on the k→jk\to j path).

To print the path i→ji\to j: start at jj, repeatedly set j←Π[i][j]j \leftarrow \Pi[i][j] until you reach ii, then reverse.

Trace on our graph (final stage): For 2→12\to1 we updated at k=4k=4: Π[2][1]=Π[4][1]\Pi[2][1]=\Pi[4][1]. Since edge 4→14\to1 exists, Π[4][1]=4\Pi[4][1]=4. So Π[2][1]=4\Pi[2][1]=4. Then Π[2][4]\Pi[2][4]: updated at k=3k=3 to Π[3][4]=3\Pi[3][4]=3. Π[2][3]=2\Pi[2][3]=2 (direct edge). Path from 2 to 1: 1←Π[2][1]=4←Π[2][4]=3←Π[2][3]=21 \leftarrow \Pi[2][1]=4 \leftarrow \Pi[2][4]=3 \leftarrow \Pi[2][3]=2. Reverse: 2→3→4→12\to3\to4\to1 ✓.

Alternative: a "next-hop" matrix N[i][j]N[i][j] (first vertex after ii); update N[i][j]=N[i][k]N[i][j]=N[i][k] when improved. Both are O(V2)O(V^2) extra space.


Warshall's Transitive Closure

Problem: for each pair (i,j)(i,j), is there any path from ii to jj? Output a boolean matrix TT.

Recurrence (boolean, using OR and AND):

tij(k)=tij(k−1)  ∨  (tik(k−1)∧tkj(k−1))t_{ij}^{(k)} = t_{ij}^{(k-1)} \;\lor\; \big(t_{ik}^{(k-1)} \land t_{kj}^{(k-1)}\big)

Base: tij(0)=1t_{ij}^{(0)} = 1 if i=ji=j or edge (i,j)(i,j) exists, else 00.

Algorithm:

for k = 1..n:
    for i = 1..n:
        for j = 1..n:
            T[i][j] = T[i][j] OR (T[i][k] AND T[k][j])

Time O(V3)O(V^3), space O(V2)O(V^2) (bits). This is exactly Floyd-Warshall with min⁡→∨\min\to\lor, +→∧+\to\land, and ∞→0\infty\to 0.

Trace on the same graph (ignore weights; edge exists = 1). Base T(0)T^{(0)}:

1234
11101
20110
30011
41001
  • k=1k=1: row 4 has T[4][1]=1T[4][1]=1; combine with row 1 → T[4][2]=1,  T[4][4]=1T[4][2]=1,\;T[4][4]=1 (already). T(1)T^{(1)}: row 4 becomes 1 1 0 1.
  • k=2k=2: rows with T[i][2]=1T[i][2]=1: rows 1,4. Row 2 = 0 1 1 0. So T[1][3]=1T[1][3]=1, T[4][3]=1T[4][3]=1. T(2)T^{(2)}: row1 1 1 1 1, row4 1 1 1 1.
  • k=3k=3: rows with T[i][3]=1T[i][3]=1: rows 1,2,4. Row 3 = 0 0 1 1. So T[1][4]=1T[1][4]=1 (already), T[2][4]=1T[2][4]=1, T[4][4]=1T[4][4]=1. T(3)T^{(3)}: row2 0 1 1 1.
  • k=4k=4: rows with T[i][4]=1T[i][4]=1: rows 1,2,3,4. Row 4 = 1 1 1 1. So T[1][1..4]=1T[1][1..4]=1 (already), T[2][1]=1T[2][1]=1, T[3][1]=1T[3][1]=1, T[3][2]=1T[3][2]=1. T(4)T^{(4)}:
1234
11111
21111
31111
41111

The graph is strongly connected — every entry is 1. ✓

Note: Warshall's algorithm is sometimes called "Floyd-Warshall for reachability." The name "Warshall" alone refers to transitive closure; "Floyd-Warshall" to shortest paths.


Johnson's Algorithm

Motivation: Dijkstra is O(Elog⁡V)O(E\log V) per source but fails on negative edges. Bellman-Ford handles negatives but is O(VE)O(VE) per source. Johnson's trick: reweight the graph so all edges become non-negative, then run Dijkstra from every vertex.

Step 1 — Add a new source ss with a 0-weight edge to every vertex.

Step 2 — Bellman-Ford from ss to compute potentials h(v)h(v) = shortest distance from ss to vv. If Bellman-Ford detects a negative cycle, stop (no solution).

Step 3 — Reweight every edge (u,v)(u,v):

w′(u,v)=w(u,v)+h(u)−h(v)w'(u,v) = w(u,v) + h(u) - h(v)

Why non-negative: by the triangle inequality of shortest paths, h(v)≤h(u)+w(u,v)h(v) \le h(u) + w(u,v), so w(u,v)+h(u)−h(v)≥0w(u,v)+h(u)-h(v) \ge 0. ✓

Why shortest paths are preserved: for any path p=v0→v1→⋯→vkp = v_0\to v_1\to\dots\to v_k, w′(p)=w(p)+h(v0)−h(vk).w'(p) = w(p) + h(v_0) - h(v_k). The added terms telescope and depend only on endpoints, so the relative order of paths between the same pair is unchanged.

Step 4 — Run Dijkstra from every vertex on w′w'. Recover true distances: d(u,v)=d′(u,v)−h(u)+h(v)d(u,v) = d'(u,v) - h(u) + h(v).

Complexity: Bellman-Ford O(VE)O(VE) + VV Dijkstras O(V⋅Elog⁡V)O(V\cdot E\log V) = O(VE+VElog⁡V)O(VE + VE\log V). With a Fibonacci heap, O(VE+V2log⁡V)O(VE + V^2\log V). With a binary heap, O(VElog⁡V)O(VE\log V).

Worked mini-example. Vertices 1,2,3. Edges: 1→21\to2 weight −2-2; 2→32\to3 weight −1-1; 1→31\to3 weight 44.

Add ss with 0-edges to 1,2,3. Bellman-Ford from ss: h(1)=0,  h(2)=−2,  h(3)=−3h(1)=0,\;h(2)=-2,\;h(3)=-3 (via s→1→2→3s\to1\to2\to3: 0−2−1=−30-2-1=-3).

Reweight:

  • 1→21\to2: −2+h(1)−h(2)=−2+0−(−2)=0-2 + h(1)-h(2) = -2 + 0 -(-2) = 0.
  • 2→32\to3: −1+h(2)−h(3)=−1+(−2)−(−3)=0-1 + h(2)-h(3) = -1 + (-2) -(-3) = 0.
  • 1→31\to3: 4+h(1)−h(3)=4+0−(−3)=74 + h(1)-h(3) = 4 + 0 -(-3) = 7.

All non-negative ✓. Dijkstra from 1 on w′w': d′(1,2)=0,  d′(1,3)=0d'(1,2)=0,\;d'(1,3)=0 (via 2). Recover: d(1,2)=0−h(1)+h(2)=0−0+(−2)=−2d(1,2)=0 - h(1)+h(2) = 0-0+(-2)=-2 ✓; d(1,3)=0−0+(−3)=−3d(1,3)=0-0+(-3)=-3 ✓.


Choosing an Algorithm (Density Table)

Let V=nV=n, E=mE=m.

SituationBest choiceTime
Single source, non-negative weightsDijkstra (binary heap)O(Elog⁡V)O(E\log V)
Single source, negative edgesBellman-FordO(VE)O(VE)
Single source, DAGTopological-order DPO(V+E)O(V+E)
All pairs, dense (E≈V2E\approx V^2), negative edges OKFloyd-WarshallO(V3)O(V^3)
All pairs, sparse (E≈VE\approx V), negative edges OKJohnsonO(VE+V2log⁡V)O(VE + V^2\log V)
All pairs, non-negative, denseFloyd-Warshall or VV×DijkstraO(V3)O(V^3)
All pairs, non-negative, sparseVV×DijkstraO(VElog⁡V)O(VE\log V)
All pairs, unweightedVV×BFSO(V(V+E))O(V(V+E))
Transitive closure onlyWarshallO(V3)O(V^3)

Rule of thumb: Floyd-Warshall wins when EE is Θ(V2)\Theta(V^2) (dense) because V3V^3 beats V⋅Elog⁡V=V3log⁡VV\cdot E\log V = V^3\log V. Johnson wins when E=o(V2/log⁡V)E = o(V^2/\log V) (sparse). For a graph with V=1000V=1000, E=2000E=2000: Floyd = 10910^9; Johnson ≈ 2×106+106⋅10≈1.2×1072\times10^6 + 10^6\cdot10 \approx 1.2\times10^7 — Johnson far better.


Multistage Graph

A multistage graph is a directed acyclic graph whose vertices are partitioned into kk stages S1,…,SkS_1,\dots,S_k, with S1={s}S_1=\{s\} (source), Sk={t}S_k=\{t\} (sink), and every edge going from a stage to a later stage. We want the shortest (or longest) s→ts\to t path.

Forward recurrence. Let c(i,j)c(i,j) = edge weight, d(i)d(i) = cost of the best i→ti\to t path. Then

d(i)=min⁡j∈next stages, (i,j)∈E(c(i,j)+d(j)),d(t)=0.d(i) = \min_{j \in \text{next stages},\,(i,j)\in E}\big(c(i,j) + d(j)\big), \qquad d(t)=0.

Compute stages backwards from SkS_k to S1S_1; answer is d(s)d(s). Time O(V+E)O(V+E) (each edge relaxed once), space O(V)O(V).

Worked 5-stage example. Stages: S1={1}S_1=\{1\}, S2={2,3}S_2=\{2,3\}, S3={4,5,6}S_3=\{4,5,6\}, S4={7,8}S_4=\{7,8\}, S5={9}S_5=\{9\}.

Edges and weights:

  • 1→21\to2: 2; 1→31\to3: 4
  • 2→42\to4: 3; 2→52\to5: 5; 3→53\to5: 2; 3→63\to6: 6
  • 4→74\to7: 4; 4→84\to8: 3; 5→75\to7: 2; 5→85\to8: 5; 6→86\to8: 1
  • 7→97\to9: 3; 8→98\to9: 2

Stage 5: d(9)=0d(9)=0.

Stage 4:

  • d(7)=3+d(9)=3d(7) = 3 + d(9) = 3.
  • d(8)=2+d(9)=2d(8) = 2 + d(9) = 2.

Stage 3:

  • d(4)=min⁡(4+d(7), 3+d(8))=min⁡(4+3, 3+2)=min⁡(7,5)=5d(4) = \min(4+d(7),\,3+d(8)) = \min(4+3,\,3+2) = \min(7,5) = 5 (via 8).
  • d(5)=min⁡(2+d(7), 5+d(8))=min⁡(2+3, 5+2)=min⁡(5,7)=5d(5) = \min(2+d(7),\,5+d(8)) = \min(2+3,\,5+2) = \min(5,7) = 5 (via 7).
  • d(6)=1+d(8)=1+2=3d(6) = 1 + d(8) = 1+2 = 3.

Stage 2:

  • d(2)=min⁡(3+d(4), 5+d(5))=min⁡(3+5, 5+5)=min⁡(8,10)=8d(2) = \min(3+d(4),\,5+d(5)) = \min(3+5,\,5+5) = \min(8,10) = 8 (via 4).
  • d(3)=min⁡(2+d(5), 6+d(6))=min⁡(2+5, 6+3)=min⁡(7,9)=7d(3) = \min(2+d(5),\,6+d(6)) = \min(2+5,\,6+3) = \min(7,9) = 7 (via 5).

Stage 1:

  • d(1)=min⁡(2+d(2), 4+d(3))=min⁡(2+8, 4+7)=min⁡(10,11)=10d(1) = \min(2+d(2),\,4+d(3)) = \min(2+8,\,4+7) = \min(10,11) = 10 (via 2).

Answer: 10. Path: 1→2→4→8→91\to2\to4\to8\to9: 2+3+3+2=102+3+3+2=10 ✓.

Backward variant: define f(j)f(j) = best s→js\to j cost, f(s)=0f(s)=0, f(j)=min⁡(i,j)∈E(f(i)+c(i,j))f(j)=\min_{(i,j)\in E}(f(i)+c(i,j)), computed stage by stage forward. Same answer, same complexity. GATE may ask either; read which direction is requested.


Longest Path: DAG vs General Graph

  • In a DAG: longest path is easy — negate weights and run the DAG shortest-path DP (topological order), or use the same recurrence with max⁡\max instead of min⁡\min. Time O(V+E)O(V+E). The multistage graph with max⁡\max is exactly this.
  • In a general graph: longest path is NP-hard (it contains Hamiltonian path as a special case). No polynomial algorithm is known. This is the classic "DAG makes it easy" contrast.

Trap: Floyd-Warshall with max⁡\max does not give longest simple paths in a general graph — it would happily traverse cycles and give unbounded/incorrect answers. Only DAGs (or graphs with no positive cycles, with care) allow the DP.


Pages 1–2 of 2