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 (rows = source, cols = destination; shown as ∞):
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 0 | 3 | ∞ | 8 |
| 2 | ∞ | 0 | 1 | ∞ |
| 3 | ∞ | ∞ | 0 | 2 |
| 4 | 5 | ∞ | ∞ | 0 |
Stage (allow vertex 1 as intermediate)
Only paths that pass through 1 can improve. Check each where :
- ; → vs → update to 8.
- ; → vs → no.
- ; → ∞, no.
- Rows 1,2,3 have (except ), so nothing else changes.
:
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 0 | 3 | ∞ | 8 |
| 2 | ∞ | 0 | 1 | ∞ |
| 3 | ∞ | ∞ | 0 | 2 |
| 4 | 5 | 8 | ∞ | 0 |
Stage (allow vertices {1,2})
Column 2 entries: ; others ∞. Row 2: .
- ; → vs → update to 4.
- ; → no.
- ; → vs → update to 9.
- ; → no.
:
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 0 | 3 | 4 | 8 |
| 2 | ∞ | 0 | 1 | ∞ |
| 3 | ∞ | ∞ | 0 | 2 |
| 4 | 5 | 8 | 9 | 0 |
Stage (allow {1,2,3})
Column 3: . Row 3: .
- ; → vs → update to 6.
- ; → vs → update to 3.
- ; → vs → no.
:
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 0 | 3 | 4 | 6 |
| 2 | ∞ | 0 | 1 | 3 |
| 3 | ∞ | ∞ | 0 | 2 |
| 4 | 5 | 8 | 9 | 0 |
Stage (allow all vertices)
Column 4: . Row 4: .
- ; → vs → no.
- ; → vs → update to 8.
- ; → vs → update to 7.
- ; → vs → update to 10.
- All other combinations through vertex 4 (e.g. , ) give no improvement.
(final):
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 0 | 3 | 4 | 6 |
| 2 | 8 | 0 | 1 | 3 |
| 3 | 7 | 10 | 0 | 2 |
| 4 | 5 | 8 | 9 | 0 |
Sanity check: = = ✓. = = ✓. = = ✓. = = ✓. The graph is strongly connected, so no entry is , matching the Warshall closure in §6.
Negative Cycle Detection
After the algorithm, if any diagonal entry , there is a negative-weight cycle (through ). Reason: a shortest path from 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 = the predecessor of on the current best path.
- Init: if and edge exists; else undefined (e.g. or NIL).
- Update: when , set (the predecessor of on the path).
To print the path : start at , repeatedly set until you reach , then reverse.
Trace on our graph (final stage): For we updated at : . Since edge exists, . So . Then : updated at to . (direct edge). Path from 2 to 1: . Reverse: ✓.
Alternative: a "next-hop" matrix (first vertex after ); update when improved. Both are extra space.
Warshall's Transitive Closure
Problem: for each pair , is there any path from to ? Output a boolean matrix .
Recurrence (boolean, using OR and AND):
Base: if or edge exists, else .
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 , space (bits). This is exactly Floyd-Warshall with , , and .
Trace on the same graph (ignore weights; edge exists = 1). Base :
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 1 | 1 | 0 | 1 |
| 2 | 0 | 1 | 1 | 0 |
| 3 | 0 | 0 | 1 | 1 |
| 4 | 1 | 0 | 0 | 1 |
- : row 4 has ; combine with row 1 → (already). : row 4 becomes
1 1 0 1. - : rows with : rows 1,4. Row 2 =
0 1 1 0. So , . : row11 1 1 1, row41 1 1 1. - : rows with : rows 1,2,4. Row 3 =
0 0 1 1. So (already), , . : row20 1 1 1. - : rows with : rows 1,2,3,4. Row 4 =
1 1 1 1. So (already), , , . :
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 1 |
| 2 | 1 | 1 | 1 | 1 |
| 3 | 1 | 1 | 1 | 1 |
| 4 | 1 | 1 | 1 | 1 |
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 per source but fails on negative edges. Bellman-Ford handles negatives but is 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 with a 0-weight edge to every vertex.
Step 2 — Bellman-Ford from to compute potentials = shortest distance from to . If Bellman-Ford detects a negative cycle, stop (no solution).
Step 3 — Reweight every edge :
Why non-negative: by the triangle inequality of shortest paths, , so . ✓
Why shortest paths are preserved: for any path , 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 . Recover true distances: .
Complexity: Bellman-Ford + Dijkstras = . With a Fibonacci heap, . With a binary heap, .
Worked mini-example. Vertices 1,2,3. Edges: weight ; weight ; weight .
Add with 0-edges to 1,2,3. Bellman-Ford from : (via : ).
Reweight:
- : .
- : .
- : .
All non-negative ✓. Dijkstra from 1 on : (via 2). Recover: ✓; ✓.
Choosing an Algorithm (Density Table)
Let , .
| Situation | Best choice | Time |
|---|---|---|
| Single source, non-negative weights | Dijkstra (binary heap) | |
| Single source, negative edges | Bellman-Ford | |
| Single source, DAG | Topological-order DP | |
| All pairs, dense (), negative edges OK | Floyd-Warshall | |
| All pairs, sparse (), negative edges OK | Johnson | |
| All pairs, non-negative, dense | Floyd-Warshall or ×Dijkstra | |
| All pairs, non-negative, sparse | ×Dijkstra | |
| All pairs, unweighted | ×BFS | |
| Transitive closure only | Warshall |
Rule of thumb: Floyd-Warshall wins when is (dense) because beats . Johnson wins when (sparse). For a graph with , : Floyd = ; Johnson ≈ — Johnson far better.
Multistage Graph
A multistage graph is a directed acyclic graph whose vertices are partitioned into stages , with (source), (sink), and every edge going from a stage to a later stage. We want the shortest (or longest) path.
Forward recurrence. Let = edge weight, = cost of the best path. Then
Compute stages backwards from to ; answer is . Time (each edge relaxed once), space .
Worked 5-stage example. Stages: , , , , .
Edges and weights:
- : 2; : 4
- : 3; : 5; : 2; : 6
- : 4; : 3; : 2; : 5; : 1
- : 3; : 2
Stage 5: .
Stage 4:
- .
- .
Stage 3:
- (via 8).
- (via 7).
- .
Stage 2:
- (via 4).
- (via 5).
Stage 1:
- (via 2).
Answer: 10. Path: : ✓.
Backward variant: define = best cost, , , 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 instead of . Time . The multistage graph with 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 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.