TExcelTAD
Home › Graph Algorithms › Johnson's Algorithm and Reweighting

Johnson's Algorithm and Reweighting

For all-pairs shortest paths on a sparse graph, Floyd-Warshall's Θ(V3)\Theta(V^3) wastes time on pairs of vertices that have nothing to do with each other. Running Dijkstra from every vertex costs O(VElg⁡V)O(VE \lg V), much less when EE is close to VV, 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 h(v)h(v), its potential, and define new weights

w^(u,v)=w(u,v)+h(u)−h(v)\hat{w}(u, v) = w(u, v) + h(u) - h(v)

Lemma. For every path p=⟨v0,v1,…,vk⟩p = \langle v_0, v_1, \ldots, v_k \rangle, w^(p)=w(p)+h(v0)−h(vk)\hat{w}(p) = w(p) + h(v_0) - h(v_k). Consequently pp is a shortest path from v0v_0 to vkv_k under ww if and only if it is one under w^\hat{w}, and GG has a negative cycle under ww if and only if it has one under w^\hat{w}.

The sum telescopes:

w^(p)=∑i=1k(w(vi−1,vi)+h(vi−1)−h(vi))=w(p)+h(v0)−h(vk)\hat{w}(p) = \sum_{i=1}^{k} \bigl( w(v_{i-1}, v_i) + h(v_{i-1}) - h(v_i) \bigr) = w(p) + h(v_0) - h(v_k)

Every path from v0v_0 to vkv_k shifts by the same amount h(v0)−h(vk)h(v_0) - h(v_k), so the order of the paths, and in particular which is lightest, does not change. A cycle has v0=vkv_0 = v_k, so its weight does not change at all. Compare that with adding a constant cc to every edge, which shifts a path of kk edges by kckc and favours paths with few edges: that is why it does not work.

Choosing the potentials

We want w^(u,v)≥0\hat{w}(u, v) \ge 0 for every edge, that is h(v)≤h(u)+w(u,v)h(v) \le h(u) + w(u, v): exactly the triangle inequality of shortest-path distances. So take distances. Add a new vertex ss with an edge of weight 0 to every vertex, run Bellman-Ford from ss, and set h(v)=δ(s,v)h(v) = \delta(s, v). 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.

text
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 d

Running time. Bellman-Ford costs O(VE)O(VE), reweighting O(E)O(E), and VV runs of Dijkstra with a binary heap O(VElg⁡V)O(VE \lg V), which dominates. With a Fibonacci heap it is O(V2lg⁡V+VE)O(V^2 \lg V + VE). For sparse graphs that beats Floyd-Warshall's Θ(V3)\Theta(V^3) by nearly a factor of V/lg⁡VV / \lg V.

Step 1: the potentials

The graph is the one from the Floyd-Warshall lesson, with the extra vertex SS. Its edges are listed first.

Step 2: the reweighted graph

With h=(hA,hB,hC,hD,hE)=(−1,0,0,0,−3)h = (h_A, h_B, h_C, h_D, h_E) = (-1, 0, 0, 0, -3) every new weight is non-negative, so Dijkstra applies. Here it runs from AA:

The program does all three steps, converts the distances back, and compares the matrix with Floyd-Warshall's.

python · try it yourself
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 AA prints the same labels as the animation. Converting back is line 8 of the pseudocode: the reweighted distance from AA to EE is 5 (along A→B→D→EA \to B \to D \to E, weights 1+4+01 + 4 + 0), and 5−h(A)+h(E)=5+1−3=35 - h(A) + h(E) = 5 + 1 - 3 = 3, which is the true distance along the same path (2+4−32 + 4 - 3). 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, V3V^3) with Johnson's (edge relaxations of Bellman-Ford plus, for the VV Dijkstra runs, edge looks and heap operations weighted by lg⁡\lg of the heap size) on random sparse graphs with negative edges.

python · try it yourself
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 E=3VE = 3V, Johnson's cost grows like V2lg⁡VV^2 \lg V while Floyd-Warshall's grows like V3V^3; 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.

cpp · try it yourself
#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 w^(u,v)=w(u,v)+h(u)−h(v)\hat{w}(u, v) = w(u, v) + h(u) - h(v), how does the weight of a path from aa to bb change?

  1. It is multiplied by h(a)h(a)
  2. It changes by h(a)−h(b)h(a) - h(b), the same for every path from aa to bb
  3. It changes by the number of edges times h(a)h(a)
  4. It does not change

Why are the reweighted edges non-negative when h(v)=δ(s,v)h(v) = \delta(s, v)?

  1. Because Bellman-Ford makes all weights positive
  2. Because shortest-path distances satisfy the triangle inequality h(v)≤h(u)+w(u,v)h(v) \le h(u) + w(u, v)
  3. Because ss has edges of weight 0
  4. Because the graph is sparse

What is the running time of Johnson's algorithm with binary heaps?

  1. Θ(V3)\Theta(V^3)
  2. O(VElg⁡V)O(VE \lg V)
  3. O(VE)O(VE)
  4. O(Elg⁡V)O(E \lg V)

Does reweighting change the weight of a cycle?

  1. Yes, it makes every cycle non-negative
  2. No: a cycle starts and ends at the same vertex, so the potentials cancel completely
  3. Only negative cycles change
  4. It doubles it