Johnson's Algorithm and Reweighting
For all-pairs shortest paths on a sparse graph, Floyd-Warshall's wastes time on pairs of vertices that have nothing to do with each other. Running Dijkstra from every vertex costs , much less when is close to , but Dijkstra needs non-negative weights. Johnson's algorithm (1977) removes that obstacle. It changes the weights so that they all become non-negative without changing which paths are shortest, using one run of Bellman-Ford. The trick, reweighting by vertex potentials, is one of the most useful ideas in graph algorithms; it reappears in min-cost flow and in the A* search heuristic.
Reweighting by potentials
Give every vertex a number , its potential, and define new weights
Lemma. For every path , . Consequently is a shortest path from to under if and only if it is one under , and has a negative cycle under if and only if it has one under .
The sum telescopes:
Every path from to shifts by the same amount , so the order of the paths, and in particular which is lightest, does not change. A cycle has , so its weight does not change at all. Compare that with adding a constant to every edge, which shifts a path of edges by and favours paths with few edges: that is why it does not work.
Choosing the potentials
We want for every edge, that is : exactly the triangle inequality of shortest-path distances. So take distances. Add a new vertex with an edge of weight 0 to every vertex, run Bellman-Ford from , and set . If Bellman-Ford finds a negative cycle, the original graph has one (the new vertex has no entering edges, so it lies on no cycle), and the algorithm stops.
JOHNSON(G, w)
1 G' = G plus a new vertex s and edges (s, v) of weight 0 for every v
2 if BELLMAN-FORD(G', w, s) == FALSE
3 report "negative cycle" and stop
4 for each vertex v: h(v) = delta(s, v) // computed by Bellman-Ford
5 for each edge (u, v): w_hat(u, v) = w(u, v) + h(u) - h(v) // >= 0
6 for each vertex u
7 run DIJKSTRA(G, w_hat, u) to get delta_hat(u, v) for all v
8 for each vertex v: d[u][v] = delta_hat(u, v) - h(u) + h(v)
9 return dRunning time. Bellman-Ford costs , reweighting , and runs of Dijkstra with a binary heap , which dominates. With a Fibonacci heap it is . For sparse graphs that beats Floyd-Warshall's by nearly a factor of .
Step 1: the potentials
The graph is the one from the Floyd-Warshall lesson, with the extra vertex . Its edges are listed first.
Step 2: the reweighted graph
With every new weight is non-negative, so Dijkstra applies. Here it runs from :
The program does all three steps, converts the distances back, and compares the matrix with Floyd-Warshall's.
import heapq
INF = float("inf")
names = "ABCDE"
edges = [("A", "B", 2), ("A", "D", 7), ("B", "C", 3), ("B", "D", 4), ("C", "A", -1),
("C", "E", 2), ("D", "C", 1), ("D", "E", -3), ("E", "B", 5)]
h = {v: 0 for v in names} # = Bellman-Ford from S, after its first pass
for _ in range(len(names)):
for u, v, w in edges:
if h[u] + w < h[v]:
h[v] = h[u] + w
assert all(h[u] + w >= h[v] for u, v, w in edges), "negative cycle"
print("potentials h:", h)
adj = {v: [] for v in names}
for u, v, w in edges:
adj[u].append((v, w + h[u] - h[v]))
print("new weights: ", ", ".join(f"{u}{v}:{w + h[u] - h[v]}" for u, v, w in edges))
def dijkstra(s):
d, done, pq = {v: INF for v in names}, set(), [(0, s)]
d[s] = 0
while pq:
du, u = heapq.heappop(pq)
if u in done:
continue
done.add(u)
for v, w in adj[u]:
if du + w < d[v]:
d[v] = du + w
heapq.heappush(pq, (d[v], v))
return d
D = {}
for u in names:
dhat = dijkstra(u)
if u == "A":
print("Dijkstra from A, new weights:", dhat)
D[u] = {v: dhat[v] - h[u] + h[v] for v in names}
fw = {u: {v: 0 if u == v else INF for v in names} for u in names}
for u, v, w in edges:
fw[u][v] = w
for k in names:
for i in names:
for j in names:
fw[i][j] = min(fw[i][j], fw[i][k] + fw[k][j])
print("distances from A, original weights:", D["A"])
print("same matrix as Floyd-Warshall:", D == fw)potentials h: {'A': -1, 'B': 0, 'C': 0, 'D': 0, 'E': -3}
new weights: AB:1, AD:6, BC:3, BD:4, CA:0, CE:5, DC:1, DE:0, EB:2
Dijkstra from A, new weights: {'A': 0, 'B': 1, 'C': 4, 'D': 5, 'E': 5}
distances from A, original weights: {'A': 0, 'B': 2, 'C': 5, 'D': 6, 'E': 3}
same matrix as Floyd-Warshall: True
The Dijkstra run from prints the same labels as the animation. Converting back is line 8 of the pseudocode: the reweighted distance from to is 5 (along , weights ), and , which is the true distance along the same path (). Every entry of the matrix agrees with Floyd-Warshall.
Sparse graphs: the count
The program compares the work of Floyd-Warshall (one unit per inner-loop step, ) with Johnson's (edge relaxations of Bellman-Ford plus, for the Dijkstra runs, edge looks and heap operations weighted by of the heap size) on random sparse graphs with negative edges.
import heapq, math, random
INF = float("inf")
def johnson_cost(n, edges):
h, work = [0] * n, 0
for _ in range(n):
changed = False
for u, v, w in edges:
work += 1
if h[u] + w < h[v]:
h[v] = h[u] + w; changed = True
if not changed:
break
adj = [[] for _ in range(n)]
for u, v, w in edges:
adj[u].append((v, w + h[u] - h[v]))
D = []
for s in range(n):
d, done, pq = [INF] * n, [False] * n, [(0, s)]
d[s] = 0
while pq:
work += max(1, math.ceil(math.log2(len(pq) + 1))) # a pop
du, u = heapq.heappop(pq)
if done[u]:
continue
done[u] = True
for v, w in adj[u]:
work += 1
if du + w < d[v]:
d[v] = du + w
work += max(1, math.ceil(math.log2(len(pq) + 1))) # a push
heapq.heappush(pq, (d[v], v))
D.append([x - h[s] + h[v] if x < INF else INF for v, x in enumerate(d)])
return D, work
def floyd(n, edges):
D = [[0 if i == j else INF for j in range(n)] for i in range(n)]
for u, v, w in edges:
D[u][v] = min(D[u][v], w)
for k in range(n):
for i in range(n):
if D[i][k] < INF:
for j in range(n):
if D[i][k] + D[k][j] < D[i][j]:
D[i][j] = D[i][k] + D[k][j]
return D, n ** 3
rng = random.Random(27)
print(f"{'V':>4} {'E':>5} {'Floyd-Warshall':>15} {'Johnson':>9}")
for n in [25, 50, 100]:
pot = [rng.randint(0, 30) for _ in range(n)]
edges = [(u, (u + 1) % n, rng.randint(0, 9) + pot[u] - pot[(u + 1) % n]) for u in range(n)]
for _ in range(2 * n):
u, v = rng.sample(range(n), 2)
edges.append((u, v, rng.randint(0, 9) + pot[u] - pot[v]))
J, cj = johnson_cost(n, edges)
F, cf = floyd(n, edges)
assert J == F
print(f"{n:>4} {len(edges):>5} {cf:>15,} {cj:>9,}") V E Floyd-Warshall Johnson
25 75 15,625 7,477
50 150 125,000 34,191
100 300 1,000,000 166,975
With , Johnson's cost grows like while Floyd-Warshall's grows like ; the gap widens with every doubling. On dense graphs the two are comparable, and Floyd-Warshall's tight loops usually win in practice.
In C++
The C++ version runs Bellman-Ford with all estimates starting at 0 (the added vertex), then Dijkstra with std::priority_queue from every vertex.
#include <climits>
#include <cstdio>
#include <functional>
#include <queue>
#include <utility>
#include <vector>
int main() {
const int n = 5;
struct E { int u, v, w; };
std::vector<E> edges = {{0,1,2}, {0,3,7}, {1,2,3}, {1,3,4}, {2,0,-1}, {2,4,2}, {3,2,1}, {3,4,-3}, {4,1,5}};
std::vector<long long> h(n, 0);
for (int pass = 0; pass < n; ++pass)
for (auto e : edges) if (h[e.u] + e.w < h[e.v]) h[e.v] = h[e.u] + e.w;
for (auto e : edges) if (h[e.u] + e.w < h[e.v]) { std::printf("negative cycle\n"); return 0; }
std::vector<std::vector<std::pair<int, long long>>> adj(n);
for (auto e : edges) adj[e.u].push_back({e.v, e.w + h[e.u] - h[e.v]});
const long long INF = LLONG_MAX / 4;
for (int s = 0; s < n; ++s) {
std::vector<long long> d(n, INF);
using Item = std::pair<long long, int>;
std::priority_queue<Item, std::vector<Item>, std::greater<Item>> pq;
d[s] = 0;
pq.push({0, s});
while (!pq.empty()) {
auto [du, u] = pq.top(); pq.pop();
if (du > d[u]) continue;
for (auto [v, w] : adj[u])
if (du + w < d[v]) { d[v] = du + w; pq.push({d[v], v}); }
}
std::printf("%c:", 'A' + s);
for (int v = 0; v < n; ++v) std::printf("%4lld", d[v] - h[s] + h[v]);
std::printf("\n");
}
}A: 0 2 5 6 3
B: 2 0 3 4 1
C: -1 1 0 5 2
D: 0 2 1 0 -3
E: 7 5 8 9 0
Test yourself
Under the reweighting , how does the weight of a path from to change?
- It is multiplied by
- It changes by , the same for every path from to
- It changes by the number of edges times
- It does not change
Why are the reweighted edges non-negative when ?
- Because Bellman-Ford makes all weights positive
- Because shortest-path distances satisfy the triangle inequality
- Because has edges of weight 0
- Because the graph is sparse
What is the running time of Johnson's algorithm with binary heaps?
Does reweighting change the weight of a cycle?
- Yes, it makes every cycle non-negative
- No: a cycle starts and ends at the same vertex, so the potentials cancel completely
- Only negative cycles change
- It doubles it