Sub topic 15
Johnson's Algorithm for Sparse All-Pairs Problems
This chapter assumes you know Bellman-Ford with negative cycle detection, Floyd-Warshall, and how Dijkstra's algorithm works with a binary heap.
Floyd-Warshall always costs O(V³), however few edges the graph has. On a sparse graph, where E is close to V, running Dijkstra once from every vertex would cost O(V·E log V), which is much less. Dijkstra cannot handle negative edges, though. Johnson's algorithm fixes this. It runs Bellman-Ford once to reweight the edges so that none are negative, then runs Dijkstra from every vertex.
The Reweighting Trick
Give every vertex a number h(v), called its potential. Then replace each edge weight with:
w'(u, v) = w(u, v) + h(u) − h(v)
For any path from s to t, the potentials of the inner vertices cancel out in the sum. That leaves w'(path) = w(path) + h(s) − h(t). The correction term depends only on the endpoints, so every s-to-t path shifts by the same amount. The shortest path under w' is therefore the shortest path under w.
To make every w' nonnegative, add a new vertex q with a 0-weight edge to every vertex. Run Bellman-Ford from q and set h(v) = dist(q, v). Shortest distances obey the triangle inequality h(v) ≤ h(u) + w(u, v), so w'(u, v) ≥ 0. If Bellman-Ford finds a negative cycle, stop, because then no shortest paths exist. Every vertex is reachable from q, so this check finds a negative cycle anywhere in the graph.
Implementation
import heapq
import math
def johnson(n, edges):
# Phase 1: Bellman-Ford from extra vertex n, edges of weight 0 to all
aug = edges + [(n, v, 0) for v in range(n)]
h = [math.inf] * (n + 1)
h[n] = 0
for _ in range(n): # n + 1 vertices, so n rounds
changed = False
for u, v, w in aug:
if h[u] + w < h[v]:
h[v] = h[u] + w
changed = True
if not changed:
break
for u, v, w in aug:
if h[u] + w < h[v]:
raise ValueError('graph contains a negative cycle')
# Phase 2: reweight so every edge is nonnegative
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w + h[u] - h[v]))
# Phase 3: Dijkstra from each source, then undo the reweighting
dist = []
for s in range(n):
d = [math.inf] * n
d[s] = 0
pq = [(0, s)]
while pq:
du, u = heapq.heappop(pq)
if du > d[u]:
continue
for v, w in adj[u]:
if du + w < d[v]:
d[v] = du + w
heapq.heappush(pq, (d[v], v))
dist.append([d[t] - h[s] + h[t] if d[t] < math.inf else math.inf
for t in range(n)])
return dist
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
print(johnson(4, edges)[0]) # [0, 4, 1, 5]For this graph, h = [0, 0, −3, 0]. The edge (1, 2, −3) becomes weight 0 and (0, 2, 5) becomes 8. All reweighted edges are nonnegative, and row 0 matches the Bellman-Ford result from earlier chapters.
When to Use It
| Algorithm | Time | Best fit |
|---|---|---|
| Floyd-Warshall | O(V³) | Dense graphs, small V, simple code |
| Johnson | O(VE log V) | Sparse graphs with negative edges |
| Dijkstra × V | O(VE log V) | All weights already nonnegative |
The usual mistake is forgetting the conversion step. Dijkstra returns d', and the true distance is d'(s, t) − h(s) + h(t).
Exercise
A graph has V = 10,000 vertices and E = 30,000 edges, some with negative weights. Roughly how do Floyd-Warshall and Johnson compare in operation count, and which should you pick?
Show answer
Floyd-Warshall needs about V³ = 10¹² operations. Johnson needs about V·E·log V ≈ 10⁴ · 3·10⁴ · 14 ≈ 4·10⁹. Johnson is roughly 200 times cheaper, so pick Johnson. It also uses O(V + E) working memory per Dijkstra run, though storing all the results still takes O(V²).
Exercise
After reweighting, why must w'(u, v) = w(u, v) + h(u) − h(v) be nonnegative when h comes from Bellman-Ford?
Show answer
h(v) is a shortest distance from q, so it satisfies the triangle inequality h(v) ≤ h(u) + w(u, v). Rearranging gives w(u, v) + h(u) − h(v) ≥ 0.