Johnson's Algorithm
–
Pseudocode
1add a new vertex q with a 0-weight edge to every vertex2h ← Bellman-Ford distances from q3if Bellman-Ford finds a negative cycle: stop4reweight every edge: w'(u, v) ← w(u, v) + h[u] − h[v] // never negative5for each vertex s: run Dijkstra from s using w'6 dist(s, v) ← dist'(s, v) − h[s] + h[v] // undo the shift
Phase
0
Dijkstra runs
0
h = −5potential from Bellman-Fordedge being reweightedDijkstra tree from s
What is Johnson's Algorithm?
Johnson's algorithm finds shortest paths between all pairs of vertices, even with negative edges, by combining the two single-source algorithms: Bellman-Ford once, then Dijkstra from every vertex.
Dijkstra can't cope with negative edges, so Johnson first reweights them. A Bellman-Ford run from an extra vertex q gives every vertex a potential h[v]. The new weight w'(u, v) = w(u, v) + h[u] − h[v] is never negative, and every path between the same two vertices changes by the same amount, so the shortest paths don't change. Run Dijkstra on the new weights and shift the answers back.
Make every weight non-negative with potentials, then Dijkstra from every vertex.
Using the Visualizer
- • Phase 1 shows the potentials h (blue labels) being computed by Bellman-Ford from the invisible vertex q.
- • Phase 2 rewrites each edge weight on the board: watch the negative weights disappear.
- • Phase 3 runs one Dijkstra per vertex and fills one row of the answer matrix each time.
- • The sample is the same graph as on the Floyd-Warshall page, so you can compare the two answers.
How It Works
1. Potentials
Bellman-Ford from a new vertex q joined to everyone by 0-weight edges.
2. Negative cycle?
If Bellman-Ford finds one, stop: no shortest paths exist.
3. Reweight
w'(u, v) = w(u, v) + h[u] − h[v] ≥ 0 for every edge.
4. Dijkstra × V
From each s, then dist(s, v) = dist'(s, v) − h[s] + h[v].
Why is w' ≥ 0? h are shortest distances from q, so h[v] ≤ h[u] + w(u, v) for every edge (otherwise h[v] could still be improved). Rearranged, that is exactly w(u, v) + h[u] − h[v] ≥ 0.
Implementation
Properties & Complexity
Time Complexity
- • Bellman-Ford once: O(V·E)
- • Dijkstra V times: O(V·(V + E) log V)
- • Total: O(V·E log V), better than O(V³) when the graph is sparse
Space & Properties
- • Answer: O(V²)
- • Working memory: O(V + E)
- • Negative edges: yes, negative cycles detected
Where It Is Used
- • All-pairs shortest paths on large sparse graphs
- • Road and network data with a few negative adjustments
- • Reweighting idea also used in min-cost flow algorithms
Limitations
- • More complex than Floyd-Warshall to implement
- • Dense graphs: Floyd-Warshall is simpler and just as fast
- • Negative cycles: no answer exists