Lesson 21 · Problem-solving methods

Johnson's Algorithm

Johnson's algorithm finds the shortest path between every pair of vertices in a directed graph that may have negative edges but no negative cycle. It reweights the edges once so they are all non-negative, then runs Dijkstra from every vertex.

Johnson's Algorithm concept diagramA visual explanation of the layout and operations shown in this lesson.reweight w' = w + h(u) − h(v) to erase negative edgesABC24−1h = 0h = 0h = −1B→C: −1 + 0 − (−1) = 0every weight ≥ 0, so Dijkstra is now safeshortest paths are unchanged: the potentials cancel along any route
1

What Johnson's Algorithm Solves

Johnson's algorithm (Donald B. Johnson, 1977) computes all-pairs shortest paths in a weighted directed graph. Negative edge weights are allowed; a negative cycle is not, since a path could loop around it forever and get ever cheaper.

The obvious options each have a problem. Dijkstra's algorithm run from every vertex is fast but gives wrong answers with negative edges. Bellman–Ford from every vertex is correct but costs O(V²E). Floyd–Warshall is O(V³) whatever the number of edges. Johnson's idea is to pay for Bellman–Ford once, then make every edge non-negative so the fast Dijkstra can do the rest.

  • All pairs, directed, negative edges allowed
  • No negative cycles
2

The Steps

  1. Add a new vertex q with a 0-weight edge to every vertex
  2. Run Bellman–Ford from q; h(v) is the distance to v. If an extra pass still improves, report a negative cycle and stop
  3. Reweight every edge: w'(u, v) = w(u, v) + h(u) − h(v), and drop q
  4. Run Dijkstra from every vertex u on the weights w'
  5. Correct each result: d(u, v) = d'(u, v) − h(u) + h(v)

The 0-weight edges make every vertex reachable from q, so one Bellman–Ford run sets h for all of them, even in a disconnected graph. They also mean every h(v) is 0 or negative.

In the tracer's graph (A→B 1, A→C 4, C→B −4, B→D 2, C→D 3), Bellman–Ford gives h = (0, −4, 0, −2). The −4 edge becomes 0, B→D becomes 0, and the others stay positive. Dijkstra from A on the new weights gives (0, 4, 4, 4), and correcting gives the real distances (0, 0, 4, 2).

  • Bellman–Ford once, Dijkstra V times
  • Correct every finite result; leave ∞ alone
3

Why Reweighting Works

No edge becomes negative. h(v) is a shortest distance, so going to u first and then taking the edge cannot beat it: h(v) ≤ h(u) + w(u, v). Rearranged, w(u, v) + h(u) − h(v) ≥ 0, which is exactly w'.

Shortest paths stay shortest. Add up w' along any path u = v₀, v₁, …, vₖ = v. Each inner h(vᵢ) appears once with + and once with −, so they cancel and the path's new weight is its old weight + h(u) − h(v). Every path between the same two vertices shifts by the same amount, so their order is unchanged, and subtracting that amount at the end gives the real distance.

Adding one constant to every edge does not work: it shifts a path by the constant times its number of edges, which favours paths with fewer edges. The potentials shift by an amount that depends only on the two ends.

  • w' ≥ 0 follows from the triangle inequality
  • Inner terms cancel: each path shifts by h(u) − h(v)
Key reference

Terms, operations, and practical uses

Reweighting

  • Super-source qA temporary vertex with a 0-weight edge to every vertex, so one Bellman–Ford run reaches them all.
  • Potential h(v)Shortest distance from q to v. Always 0 or negative, because of the 0-weight edges.
  • Reweighted edgew'(u, v) = w(u, v) + h(u) − h(v). Never negative when there is no negative cycle.

Shortest paths

  • Bellman–Ford passRun once from q in O(VE). An improvement on the V-th pass means a negative cycle.
  • Repeated DijkstraOne run per source on w', O(E log V) each with a binary heap.
  • Correctiond(u, v) = d'(u, v) − h(u) + h(v), applied only to finite distances.

Safety

  • Negative cycleA cycle of negative total weight. Shortest paths through it are undefined, so the algorithm stops.
  • Telescoping sumAlong a path the inner h terms cancel, so the path's weight changes by h(u) − h(v) only.
  • Infinite distanceUnreachable pairs stay ∞; never add potentials to the ∞ sentinel.
Implementation

Code in Python, C++ and Java

import heapq

names = "ABCD"
n = 4
edges = [(0, 1, 1), (0, 2, 4), (2, 1, -4), (1, 3, 2), (2, 3, 3)]
INF = float("inf")

# Bellman-Ford from q: starting every h at 0 stands for q's 0-weight edges
h = [0] * n
for _ in range(n - 1):
    for u, v, w in edges:
        h[v] = min(h[v], h[u] + w)
if any(h[u] + w < h[v] for u, v, w in edges):
    raise SystemExit("negative cycle")

adj = [[] for _ in range(n)]
for u, v, w in edges:
    adj[u].append((v, w + h[u] - h[v]))

for s in range(n):
    d = [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))
    row = [str(d[v] - h[s] + h[v]) if d[v] < INF else "INF" for v in range(n)]
    print(names[s], " ".join(row))
#include <array>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;

int main() {
    string names = "ABCD";
    int n = 4;
    vector<array<long long, 3>> edges = {{0, 1, 1}, {0, 2, 4}, {2, 1, -4}, {1, 3, 2}, {2, 3, 3}};
    const long long INF = 1e18;

    vector<long long> h(n, 0);
    for (int i = 0; i < n - 1; i++)
        for (auto [u, v, w] : edges) h[v] = min(h[v], h[u] + w);
    for (auto [u, v, w] : edges)
        if (h[u] + w < h[v]) { cout << "negative cycle\n"; return 0; }

    vector<vector<pair<int, long long>>> adj(n);
    for (auto [u, v, w] : edges) adj[u].push_back({(int)v, w + h[u] - h[v]});

    for (int s = 0; s < n; s++) {
        vector<long long> d(n, INF);
        priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> 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}); }
        }
        cout << names[s];
        for (int v = 0; v < n; v++) {
            if (d[v] < INF) cout << ' ' << d[v] - h[s] + h[v];
            else cout << " INF";
        }
        cout << '\n';
    }
}
import java.util.*;

class Main {
    public static void main(String[] args) {
        String names = "ABCD";
        int n = 4;
        long[][] edges = {{0, 1, 1}, {0, 2, 4}, {2, 1, -4}, {1, 3, 2}, {2, 3, 3}};
        final long INF = Long.MAX_VALUE / 4;

        long[] h = new long[n];
        for (int i = 0; i < n - 1; i++)
            for (long[] e : edges) h[(int) e[1]] = Math.min(h[(int) e[1]], h[(int) e[0]] + e[2]);
        for (long[] e : edges)
            if (h[(int) e[0]] + e[2] < h[(int) e[1]]) { System.out.println("negative cycle"); return; }

        List<List<long[]>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
        for (long[] e : edges) adj.get((int) e[0]).add(new long[]{e[1], e[2] + h[(int) e[0]] - h[(int) e[1]]});

        for (int s = 0; s < n; s++) {
            long[] d = new long[n];
            Arrays.fill(d, INF);
            d[s] = 0;
            PriorityQueue<long[]> pq = new PriorityQueue<>(Comparator.comparingLong(a -> a[0]));
            pq.add(new long[]{0, s});
            while (!pq.isEmpty()) {
                long[] top = pq.remove();
                int u = (int) top[1];
                if (top[0] != d[u]) continue;
                for (long[] e : adj.get(u)) {
                    int v = (int) e[0];
                    if (top[0] + e[1] < d[v]) { d[v] = top[0] + e[1]; pq.add(new long[]{d[v], v}); }
                }
            }
            StringBuilder row = new StringBuilder().append(names.charAt(s));
            for (int v = 0; v < n; v++) row.append(' ').append(d[v] < INF ? String.valueOf(d[v] - h[s] + h[v]) : "INF");
            System.out.println(row);
        }
    }
}
Watch it run

Step through it

Running on A→B 1, A→C 4, C→B −4, B→D 2, C→D 3

all-pairs shortest paths with a negative edge14−423A0B1 (true 0)CD3 (true 2)Dijkstra from A: B = 1, D = 3true: B = 0 via C, D = 2one negative edge breaks Dijkstra
Step 1

Negative edge: Dijkstra fails

We want the shortest distance between every pair of vertices. Running Dijkstra from A on the raw weights settles B at 1 and then D at 3, because it assumes a settled vertex can never get cheaper. The path A → C → B costs 4 − 4 = 0, but by the time C is popped, B is already final.

Output
1 / 11
4

Time and Space Complexity

Bellman–Ford costs O(VE). V runs of Dijkstra with a binary heap cost O(V·E log V), which dominates; with a Fibonacci heap they cost O(V² log V + VE). The output alone is a V × V matrix, so memory is Θ(V²) for the answers plus O(V + E) for the graph.

For a sparse graph, where E is about V, that is about V² log V, far below V³. With V = 10,000 and E = 50,000, Johnson's algorithm needs roughly 7 × 10⁹ basic steps in the worst case against 10¹² for Floyd–Warshall.

  • O(VE log V) with a binary heap
  • Wins when E is much smaller than V²
5

Johnson vs Floyd–Warshall

Both find all-pairs shortest paths and both allow negative edges without negative cycles. The choice comes down to density and simplicity: Floyd–Warshall is three nested loops over a matrix, Johnson's algorithm needs Bellman–Ford, a heap and adjacency lists. If every weight is already non-negative, skip the reweighting and just run Dijkstra from every vertex.

Johnson vs Floyd–Warshall
JohnsonFloyd–Warshall
TimeO(VE log V)O(V³)
Best forSparse graphsDense graphs, small V
Graph formAdjacency listAdjacency matrix
Negative cycleFound by Bellman–FordNegative entry on the diagonal
Code sizeLargerThree loops
  • Sparse: Johnson; dense or tiny: Floyd–Warshall
  • All weights ≥ 0: plain Dijkstra from each vertex
6

Edge Cases and Bugs

Forgetting the correction reports distances in the reweighted graph: in the example, 4 instead of 2 for A → D. Correcting ∞ turns unreachable pairs into large wrong numbers; check for ∞ first. Overflow: w + h(u) − h(v) can exceed the range of a 32-bit int even when final answers fit, so use 64-bit values.

Paths can be rebuilt from each Dijkstra run's parent array, since reweighting does not change which path is shortest. q must not appear in the output. Test with a disconnected graph, a negative cycle in a part not reachable from some vertices (Bellman–Ford from q still finds it), parallel edges and negative final distances, and compare small cases with Floyd–Warshall.

  • Undo h on every finite distance
  • Use 64-bit weights