Johnson’s algorithm for shortest paths in sparse graphs
Finding the shortest route between every pair of vertices is a common graph problem. In a road network, this might mean calculating travel costs between every warehouse and delivery suburb. In a software dependency graph, it can mean measuring the cheapest chain of transformations between all components.
Johnson’s algorithm is designed for this all-pairs shortest paths problem when the graph is sparse and may contain negative edge weights. It combines Bellman–Ford with repeated Dijkstra searches, using a clever reweighting step to preserve shortest paths while removing negative weights.
The method is particularly useful when the number of edges is much smaller than the square of the number of vertices. That situation occurs in many practical networks: a large set of locations may have only a few direct roads, transit connections, or communication links per location.
This tutorial develops the algorithm from its assumptions through to implementation details, complexity analysis, and testing. The examples use directed weighted graphs, although the same ideas apply to undirected graphs when their weights satisfy the required conditions.
Why Johnson’s algorithm is useful
Suppose a graph has (V) vertices and (E) edges. A straightforward solution runs a shortest-path algorithm from every vertex. Dijkstra’s algorithm is efficient for non-negative weights, but it cannot safely handle negative edges. Floyd–Warshall handles negative edges, yet its (O(V^3)) running time can be expensive for a sparse graph.
Johnson’s algorithm takes a different route. It first runs Bellman–Ford once to calculate a potential value for every vertex. These potentials transform each edge weight into a non-negative value. Dijkstra’s algorithm can then be run from every source vertex.
Negative edges can represent discounts, credits, rebates, or other reductions in cost. They are valid as long as the graph contains no negative-weight cycle. A negative cycle would allow the path cost to decrease indefinitely, so a well-defined shortest path would not exist for affected vertices.
For example, a transport model covering Sydney, Melbourne, and smaller regional hubs might assign a negative adjustment to a preferred freight corridor. Johnson’s method can still process that model, provided no sequence of connections loops back with a total negative cost.
Graph representation and assumptions
Use a directed graph (G=(V,E)), where each edge ((u,v)) has a weight (w(u,v)). An adjacency list is the natural representation for a sparse graph because it stores only existing edges. A matrix would reserve space for every possible pair, including the many absent connections.
The algorithm supports unreachable pairs. If no route leads from (u) to (v), the final distance remains infinity. This is important for disconnected networks, such as separate transport regions or isolated clusters of services.
There are three important assumptions:
- Edge weights may be negative, but there must be no negative-weight cycle.
- Vertex identifiers must be consistent across the adjacency list and distance arrays.
- Arithmetic must safely represent infinity and the largest possible path cost.
In Python, a graph can be stored as a dictionary whose values are lists of (neighbour, weight) pairs. Readers building that representation can reinforce their language fundamentals through Python programming, especially list handling, dictionaries, loops, and priority queues.
Reweighting edges with Bellman–Ford
Add a new source vertex (q) and connect it to every original vertex with an edge of weight zero. Run Bellman–Ford from (q). Let (h(v)) be the resulting shortest distance from (q) to vertex (v).
Because (q) has a zero-weight edge to every vertex, every original vertex is reachable. Bellman–Ford either detects a negative cycle or produces a finite potential (h(v)) for each vertex.
For every original edge ((u,v)), calculate its reweighted cost:
[ w'(u,v)=w(u,v)+h(u)-h(v) ]
The triangle inequality from Bellman–Ford gives:
[ h(v)\leq h(u)+w(u,v) ]
Rearranging this inequality shows that (w'(u,v)\geq 0). This is the key property that permits Dijkstra’s algorithm to run safely.
The reweighting does not change which route is shortest. For any path from (s) to (t), the potential terms cancel across consecutive edges, leaving:
[ w'(P)=w(P)+h(s)-h(t) ]
Every path between the same endpoints receives the same constant adjustment. Therefore, the path with minimum original weight is also the path with minimum reweighted weight.
Running Dijkstra from every source
After reweighting, run Dijkstra’s algorithm once for each original vertex. A binary heap priority queue gives the familiar sparse-graph implementation. When an edge offers a shorter tentative distance, push the updated pair onto the heap.
The distances returned by Dijkstra are reweighted distances, so convert each result back using:
[ d(s,t)=d'(s,t)-h(s)+h(t) ]
Here, (d'(s,t)) is the Dijkstra result, while (d(s,t)) is the original shortest-path distance. Forgetting this correction is one of the most common implementation errors: the selected routes may look correct, but the reported costs will be wrong.
| Approach | Negative edges | Negative-cycle detection | Typical sparse-graph cost | Best use |
|---|---|---|---|---|
| Dijkstra from every vertex | No | No | (O(VE\log V)) | Non-negative weights |
| Bellman–Ford from every vertex | Yes | Yes | (O(V^2E)) | Few sources or small graphs |
| Floyd–Warshall | Yes | Yes | (O(V^3)) | Dense graphs and simple matrix code |
| Johnson’s algorithm | Yes | Yes | (O(VE+VE\log V)) | Sparse graphs with many sources |
A practical Dijkstra routine should ignore stale heap entries. If a pair (distance, vertex) is popped and its distance is larger than the current best known value, skip it. This lazy approach avoids needing a decrease-key operation.
A Python implementation pattern
The implementation can be divided into three independent functions: Bellman–Ford, Dijkstra, and the Johnson driver. Keeping these stages separate makes the invariants easier to inspect and makes unit testing more focused.
Bellman–Ford usually starts all distances at infinity, assigns zero to the artificial source, and relaxes every edge up to (V-1) times. An additional pass checks whether any edge can still be relaxed. If it can, the graph contains a negative cycle.
Dijkstra receives the reweighted adjacency list and a source. A compact pattern looks like this:
from heapq import heappush, heappop
from math import inf
def dijkstra(graph, source):
best = {vertex: inf for vertex in graph}
best[source] = 0
heap = [(0, source)]
while heap:
distance, vertex = heappop(heap)
if distance != best[vertex]:
continue
for neighbour, weight in graph[vertex]:
candidate = distance + weight
if candidate < best[neighbour]:
best[neighbour] = candidate
heappush(heap, (candidate, neighbour))
return best
The Johnson driver first adds the artificial source conceptually, obtains the potentials, creates reweighted edges, and then applies the conversion formula to every Dijkstra result. If the original graph contains vertices with no outgoing edges, they must still appear as keys in the adjacency structure.
Implementation checks
- Use a fresh distance map for every Bellman–Ford and Dijkstra run.
- Keep original edge weights available when constructing final answers.
- Check for negative cycles before calling Dijkstra.
- Preserve unreachable values as infinity rather than converting them to zero.
- Use a sufficiently wide numeric type for accumulated path costs.
Complexity and memory requirements
Bellman–Ford takes (O(VE)) time on the graph with the artificial source. Dijkstra with a binary heap takes (O(E\log V)) for one source in the usual sparse representation. Running it from all (V) vertices costs (O(VE\log V)), giving Johnson’s overall bound:
[ O(VE+VE\log V) ]
For a connected sparse graph where (E) is close to (V), this is roughly (O(V^2\log V)). Floyd–Warshall may be preferable when (E) approaches (V^2), because its predictable cubic cost can be competitive and its matrix implementation is straightforward.
The adjacency list uses (O(V+E)) memory. Storing every all-pairs distance requires (O(V^2)) additional space. If the application needs only selected source vertices, the Dijkstra phase can be adapted to retain fewer results.
A binary heap is usually the practical choice in Python. More specialised priority queues can improve theoretical bounds in some models, but their constant factors and implementation complexity may make them less attractive for ordinary programs.
Testing and common mistakes
A strong test suite should include simple positive-weight graphs, graphs containing negative edges, disconnected components, duplicate edges, and vertices with no outgoing edges. Include a graph where the cheapest route uses several edges rather than the direct edge, since this checks both relaxation and reweighting.
Compare Johnson’s output with a trusted reference on small graphs. Floyd–Warshall is useful for this purpose because it provides an independent all-pairs calculation. Random graph tests can generate small weights, while a separate check rejects cases with negative cycles.
Cases worth checking
- A single vertex with no edges.
- Two vertices connected in only one direction.
- Parallel edges where one is cheaper.
- A negative edge that does not form a cycle.
- A reachable negative cycle that must raise an error.
- An unreachable pair whose result should remain infinity.
Typical bugs include adding the artificial source incorrectly, running Dijkstra before reweighting, and applying the recovery formula with the signs reversed. Another mistake is treating a stale priority-queue entry as authoritative, which can cause unnecessary work or incorrect processing.
The same habit of checking intermediate values is useful across computer science. For example, tracing potentials, tentative distances, and final corrections has a similar educational value to inspecting gradients and parameter updates in a backpropagation review.
Practical applications in Australian networks
Johnson’s algorithm suits large sparse networks in the Australian market. A delivery platform might model warehouses, parcel lockers, supermarkets, and suburbs, where each site connects to only a small number of nearby or commercially relevant locations. Repeated shortest-path queries can then support dispatch planning and cost estimation.
Public transport gives another intuitive example. Sydney’s rail and bus connections, Melbourne’s tram network, and Brisbane’s bus corridors form sparse graphs relative to the number of possible station or stop pairs. Edge weights could represent travel time, transfers, or a monetary cost, with negative adjustments used for modelling credits or preferred service links.
Real deployments also need to respect local operating conditions. Australian systems may process location or customer data under the Privacy Act 1988, so graph identifiers should be separated from personally identifying information. Everyday travel patterns, such as tapping on with an Opal or Myki card and changing services during peak periods, can produce time-dependent costs that require a more advanced model than a static Johnson graph.
For a static weighted network with many source-destination queries, however, the algorithm remains a valuable combination of ideas: Bellman–Ford handles the difficult weights, reweighting creates a non-negative problem, and Dijkstra efficiently explores the sparse structure.