Dijkstra’s algorithm with priority queue optimisation
Shortest-path tasks often begin with a map, a network, or a set of weighted choices. A city street, a train line, and a computer network can all be modelled as a graph, with vertices representing locations and edges representing allowable moves. Dijkstra’s algorithm finds the least-cost route from a source when every edge weight is non-negative. A min-priority queue decides which frontier vertex to settle next, avoiding repeated scans of every known distance.
For a wider algorithmic foundation, hello ML’s problem-solving guides cover graph traversal, recurrence, and complexity analysis. The implementation below uses Python’s standard-library heap and keeps the returned predecessor map separate from the distance map, allowing a route to be reconstructed without changing the search logic.
Model the route as a weighted graph
An edge weight can represent distance, travel time, cost, or another penalty. For a directed graph, an edge from A to B does not imply a reverse edge; for an undirected graph, add it in both directions. The source vertex begins the search, while the target is optional when all reachable distances are required. Every edge must have a non-negative weight, including zero-weight edges, which are valid but can create ties.
Australian maps make these distinctions concrete. A trip might connect Queen Victoria Market, Melbourne’s CBD, South Bank, Richmond, and St Kilda, with another network around Sydney’s Central Station and Circular Quay. Distances are quoted in kilometres and speed limits in km/h, so edge weights need a consistent unit. Australia’s left-hand traffic and one-way streets can also make a route directional: the fastest outward path is not automatically the best return journey.
Store the network as an adjacency list: each vertex maps to its outgoing neighbours and edge weights. A dictionary-of-dictionaries is convenient in Python, while arrays of edge records are common in compiled languages. This representation visits each edge once during exploration, giving O(V+E) graph storage and traversal work before the queue operations are counted.
Establish the distance and relaxation rules
Initialisation assigns zero to the source and infinity to every other vertex. The predecessor map starts empty because no route has yet been proved. When a vertex is processed, its outgoing edges are examined. For an edge from u to v with weight w, the candidate route costs distance[u] + w. If that candidate is smaller than distance[v], update the distance and record u as v’s predecessor.
This update is called relaxation. It does not finalise a neighbour; it only stores a better route found so far. A later vertex may produce an even smaller candidate, so several tentative distances for one graph vertex can exist over the lifetime of the search. That observation is central to an efficient heap implementation: obsolete entries must not be allowed to trigger extra work.
The source is settled when its zero-cost entry is removed from the priority queue. A vertex is likewise settled when its smallest current entry is removed and is not stale. If the target is removed and settled, the search may stop because no later non-negative path can improve it. If the queue empties first, every reachable vertex has been settled and unreachable vertices retain an infinite distance.
Replace repeated scans with a min-heap
A plain array implementation repeatedly searches all vertices for the smallest tentative distance, adding O(V²) work to dense graphs. A binary min-heap supports extraction in logarithmic time and makes the algorithm O((V+E) log V) for a simple graph. The heap stores tuples of tentative distance and vertex, with the distance first so Python orders them by cost.
The following Python implementation uses heapq and lazy deletion. Instead of locating and replacing an existing heap entry after relaxation, it pushes the improved candidate and discards an older entry when it eventually reaches the front.
import heapq
def dijkstra(graph, source):
if any(
weight < 0
for neighbours in graph.values()
for weight in neighbours.values()
):
raise ValueError("Edge weights must be non-negative")
distances = {node: float("inf") for node in graph}
previous = {}
distances[source] = 0
heap = [(0, source)]
while heap:
distance, node = heapq.heappop(heap)
if distance != distances[node]:
continue
for neighbour, weight in graph[node].items():
candidate = distance + weight
if candidate < distances[neighbour]:
distances[neighbour] = candidate
previous[neighbour] = node
heapq.heappush(heap, (candidate, neighbour))
return distances, previous
def restore_path(previous, source, target):
path = [target]
while path[-1] != source:
path.append(previous[path[-1]])
return path[::-1]
When a pop is stale, its stored distance is greater than the best distance currently known for that vertex, so the equality check skips it. A valid pop settles the vertex and relaxes each outgoing edge. No separate visited set is required because a settled vertex cannot receive a strictly better distance under non-negative weights.
The implementation uses O((V+E) log V) time and O(V+E) total space, including the graph, distance map, predecessor map, and potentially O(E) heap entries. After checking that the target is reachable, restore_path follows predecessors from the target back to the source.
Compare priority queue designs
Queue choice affects constant factors, memory use, and the cleanest way to represent a decrease-key operation. Dense graphs may tolerate a linear scan, while sparse road and network graphs benefit from logarithmic extraction. The relevant choices differ mainly in how they handle a newly improved distance.
| Design | Extract minimum | Improve a key | Overall bound | Practical fit |
|---|---|---|---|---|
| Linear scan | O(V) | O(1) | O(V² + E) | Small, dense graphs |
heapq with lazy deletion |
O(log V) | O(log V) via another push | O((V+E) log V) | General Python graphs |
| Indexed binary heap | O(log V) | O(log V) | O((V+E) log V) | One active entry per vertex |
| Fibonacci heap | O(log V) amortised | O(1) amortised | O(E + V log V) | Specialist or theoretical use |
For most Python programs, heapq is the practical default because it is fast, standard, and requires no custom tree. It does not expose an efficient decrease-key operation, so lazy deletion is the usual compromise. An indexed binary heap keeps one mutable entry per vertex and performs explicit decrease-key, which can reduce heap size in graphs with many repeated improvements.
A database planner makes a similar choice: query explain plans show whether a planner selected a cheaper execution route, while suitable indexes can reduce the work needed to find it. Dijkstra’s queue and a database planner solve different problems, but both benefit from choosing an efficient next action rather than repeatedly checking every option.
Trace a shortest route through Melbourne
Consider an illustrative walking graph with four vertices: Queen Victoria Market (Q), Melbourne CBD (C), Richmond (R), and South Bank (S). The directed edges are Q→C at 0.8 km, C→S at 1.0 km, Q→R at 1.4 km, and R→S at 1.3 km. They are pedagogical weights rather than turn-by-turn navigation distances.
The source Q receives distance zero. Relaxing its edges gives C a tentative distance of 0.8 km and R a tentative distance of 1.4 km. The heap removes C first, which creates a candidate of 1.8 km for South Bank. It then removes R at 1.4 km; the route through R to S costs 2.7 km, so it cannot replace the 1.8 km candidate. South Bank is removed last with the winning route Q→C→S.
A real transport model may weight edges by minutes rather than kilometres. If a service is “runnin’ late”, a time-dependent update can raise that edge’s cost; an arvo service may use a different timetable. Melbourne’s Myki and Sydney’s Opal fare systems make journey planning part of everyday transport decisions, while state agencies, operators and councils shape service coverage. Ride-hailing platforms operating in Australia also use route and delay estimates when matching riders with drivers.
That practical perspective fits hello ML’s about the project, which describes a community-written educational blog with open access rather than a commercial course catalogue. Sharing tested examples lets readers compare implementations, challenge assumptions and adapt the method to Australian datasets.
Recommendations for a reliable implementation
Before using the algorithm in a service, fix the graph contract, the unit of each weight, and the expected output. A robust result should expose the best distance, a predecessor chain when a target is reachable, and a clear signal for an unreachable target. Complexity claims should match the chosen queue and graph representation.
- Validate all edge weights before exploration; reject negative values because Dijkstra’s greedy settlement rule depends on non-negative costs.
- Prefer adjacency lists for sparse graphs, and state whether each edge is directed or can be traversed in both directions.
- Use
heapqfor Python, push(distance, vertex)tuples, and discard stale entries before relaxing outgoing edges. - Keep predecessor assignments tied to strict distance improvements so a later, worse candidate cannot overwrite a valid path.
- Test a single-vertex graph, zero-weight edges, disconnected components, ties, and a target reached through competing routes.
- Document whether weights mean kilometres, minutes, cents, or another unit; Australian route data commonly uses kilometres and km/h.
Together, the distance map, predecessor map, and efficient min-heap form a compact solution with predictable O((V+E) log V) behaviour for simple sparse graphs. The greedy choice is safe because no unexplored path can become cheaper once its smallest frontier vertex has been settled under non-negative weights. This combination supports everything from classroom examples to routing services used across Australia.