Sub topic 15
Johnson's Algorithm for Sparse All-Pairs Problems
This chapter assumes you already know the Bellman-Ford implementation and the Floyd-Warshall recurrence from earlier chapters. It also assumes you know how Dijkstra's algorithm works with a binary heap, and why it fails on negative edges.
Floyd-Warshall solves all-pairs shortest paths in O(V³) time, whatever the number of edges. On a dense graph that is hard to beat. Many real graphs are sparse, though. Road networks, dependency graphs and communication networks often have E close to V, not close to V². On such graphs, running Dijkstra once from every vertex costs about O(V · E log V), which is much less than V³. Dijkstra cannot run on negative edges, so that plan fails as soon as one edge is negative.
Johnson's algorithm fixes this. It runs Bellman-Ford once to compute a "potential" for each vertex. It then uses the potentials to rewrite every edge weight as a nonnegative number, without changing which paths are shortest. After that, Dijkstra can run safely from every source.
The Reweighting Idea
Give every vertex v a number h(v). Replace each edge weight with:
w'(u, v) = w(u, v) + h(u) − h(v)
Two properties make this useful.
Property 1: Shortest paths do not change
Take any path p = v₀ → v₁ → … → vₖ. Sum the new weights along it:
w'(p) = Σ [w(vᵢ, vᵢ₊₁) + h(vᵢ) − h(vᵢ₊₁)] = w(p) + h(v₀) − h(vₖ)
The inner h terms cancel in pairs, so the sum telescopes. Every path from v₀ to vₖ is shifted by the same constant, h(v₀) − h(vₖ). The ranking of paths between a fixed pair of endpoints therefore stays the same, and the shortest path under w' is also the shortest under w. To recover the true distance, undo the shift:
d(u, v) = d'(u, v) − h(u) + h(v)
Cycles get the same treatment. A cycle starts and ends at the same vertex, so its shift is zero, and a negative cycle stays negative after reweighting.
Property 2: The right h makes every edge nonnegative
The shift only helps if it makes every w' nonnegative. Shortest-path distances have the triangle inequality: for every edge (u, v), d(v) ≤ d(u) + w(u, v). If h(v) is the shortest distance to v from some fixed source, then:
w'(u, v) = w(u, v) + h(u) − h(v) ≥ 0
The algorithm needs a source that reaches every vertex. Johnson adds a new vertex q with a zero-weight edge from q to every original vertex. Bellman-Ford from q then gives h(v) = d(q, v) for all v. These values are always ≤ 0, because the direct edge from q costs 0.
Implementation
The code below is self-contained. It includes the Bellman-Ford routine from the earlier chapter, so it runs as shown.
import heapq
import math
def bellman_ford(n, edges, source):
dist = [math.inf] * n
dist[source] = 0
for _ in range(n - 1):
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
if not changed:
break
for u, v, w in edges:
if dist[u] + w < dist[v]:
raise ValueError('negative cycle in graph')
return dist
def dijkstra(n, adj, source):
dist = [math.inf] * n
dist[source] = 0
heap = [(0, source)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue # stale heap entry
for v, w in adj[u]:
nd = d + w
if nd < dist[v]:
dist[v] = nd
heapq.heappush(heap, (nd, v))
return dist
def johnson(n, edges):
# Step 1: add vertex q = n with 0-weight edges to every vertex
q = n
augmented = edges + [(q, v, 0) for v in range(n)]
h = bellman_ford(n + 1, augmented, q)
# Step 2: reweight so every edge is nonnegative
adj = [[] for _ in range(n)]
for u, v, w in edges:
w2 = w + h[u] - h[v]
adj[u].append((v, w2))
# Step 3: Dijkstra from every vertex, then undo the shift
result = []
for s in range(n):
d2 = dijkstra(n, adj, s)
row = [d2[t] - h[s] + h[t] if d2[t] != math.inf else math.inf
for t in range(n)]
result.append(row)
return h, result
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
h, dist = johnson(4, edges)
print(h) # [0, 0, -3, 0, 0]
for row in dist:
print(row)
# [0, 4, 1, 5]
# [inf, 0, -3, 1]
# [inf, inf, 0, 4]
# [inf, inf, inf, 0]The output matches the Floyd-Warshall result for the same graph. The last entry of h belongs to q itself.
Tracing the reweighting
With h = [0, 0, −3, 0], the edges become:
| Edge | w | h(u) − h(v) | w' |
|---|---|---|---|
| 0 → 1 | 4 | 0 − 0 | 4 |
| 0 → 2 | 5 | 0 − (−3) | 8 |
| 1 → 2 | −3 | 0 − (−3) | 0 |
| 2 → 3 | 4 | −3 − 0 | 1 |
| 1 → 3 | 6 | 0 − 0 | 6 |
Every w' is nonnegative. Edges that lie on a shortest path from q, such as 1 → 2, become exactly 0. Dijkstra from 0 finds d'(0, 3) = 4 + 0 + 1 = 5, and converting back gives 5 − h(0) + h(3) = 5.
Complexity and When It Wins
| Phase | Cost |
|---|---|
| Bellman-Ford on augmented graph | O(V · E) |
| Reweighting | O(E) |
| V runs of Dijkstra, binary heap | O(V · (V + E) log V) |
| Total, binary heap | O(V · E log V) for connected graphs |
| Total, Fibonacci heap | O(V² log V + V · E) |
Compare this with Floyd-Warshall's O(V³):
| Graph | Johnson (binary heap) | Floyd-Warshall | Better choice |
|---|---|---|---|
| Sparse, E ≈ V | about V² log V | V³ | Johnson |
| Medium, E ≈ V^1.5 | about V^2.5 log V | V³ | Johnson, usually |
| Dense, E ≈ V² | about V³ log V | V³ | Floyd-Warshall |
For V = 10,000 and E = 50,000, Johnson does on the order of 10⁹ basic steps. Floyd-Warshall needs 10¹² inner-loop iterations. On dense graphs, Floyd-Warshall's simple triple loop has small constants and reads memory in a cache-friendly order, so it wins even when the asymptotic costs are close.
Gotchas and Failure Modes
Negative cycles are caught globally
Vertex q reaches every vertex, so Bellman-Ford from q detects a negative cycle anywhere in the graph, including in parts that no particular source can reach. Floyd-Warshall can report which pairs are affected. Johnson, as written, gives up on the whole graph. If you need distances for the pairs a cycle does not affect, Floyd-Warshall gives them to you more directly.
Floating-point weights
With real-valued weights, rounding can make w' come out as something like −1e−16. Dijkstra usually tolerates tiny negatives, but its correctness argument no longer holds. A common fix is to clamp: w2 = max(0.0, w + h[u] - h[v]), or to apply that clamp only within a small tolerance.
Path reconstruction comes for free
Reweighting keeps the same shortest paths, so the predecessor tree that Dijkstra builds on w' is a valid shortest-path tree for w. Store one predecessor array per source. Together they give a V × V predecessor matrix, which plays the same role as the next-hop matrix from Floyd-Warshall.
Graph updates
The potentials h depend on every edge. Adding an edge or lowering a weight can make some w' negative, so you must run Bellman-Ford again. Raising a weight keeps h valid, because the triangle inequality still holds.
Parallelism and memory
The V Dijkstra runs are independent of each other. They split across threads or machines with no coordination, which Floyd-Warshall's k-loop does not allow. If you only need distances from some sources, run Dijkstra from just those. That flexibility is a practical reason to prefer Johnson even for single-source-heavy query patterns on graphs with negative edges. You pay for Bellman-Ford once and then answer each source query at Dijkstra speed.
Exercise
A graph has edges (0→1, w=2), (1→2, w=−4), (0→2, w=1). Compute h using the extra vertex q, then give the reweighted weight of every edge and confirm that all of them are nonnegative.
Show answer
From q, every vertex starts at 0. h(0)=0, h(1)=min(0, 0+2)=0, h(2)=min(0, h(1)−4, h(0)+1)=−4. Reweighted: 0→1: 2+0−0=2; 1→2: −4+0−(−4)=0; 0→2: 1+0−(−4)=5. All are nonnegative. Check: d'(0,2)=min(5, 2+0)=2, and d(0,2)=2−h(0)+h(2)=2−0−4=−2, which matches the path 0→1→2 with weight 2−4=−2.
Exercise
You have a graph with V = 2,000 vertices and E = 3,000,000 edges, some of them negative, and you need all-pairs distances. Should you use Johnson's algorithm or Floyd-Warshall? Justify with rough operation counts.
Show answer
The graph is nearly dense (V² = 4,000,000). Floyd-Warshall needs V³ = 8×10⁹ simple steps. Johnson with a binary heap needs about V·E·log V ≈ 2,000 × 3×10⁶ × 11 ≈ 6.6×10¹⁰ steps, plus V·E = 6×10⁹ for Bellman-Ford. Floyd-Warshall is the better choice. It also has smaller constants and better cache behavior.
Exercise
Why must the potentials h come from shortest distances, rather than from arbitrary numbers, for Johnson's algorithm to work? Which of the two reweighting properties still holds with arbitrary h?
Show answer
For any h, path weights shift by h(start) − h(end), so shortest paths are preserved (Property 1 holds). Nonnegativity (Property 2) needs h(v) ≤ h(u) + w(u,v) for every edge, which is the triangle inequality. Shortest-path distances satisfy it, but arbitrary numbers usually do not, and then some w' would be negative and Dijkstra would be unsafe.