Dijkstra's algorithm
Implement Dijkstra's algorithm with a min-heap to find shortest distances from a source, then reconstruct the full path.
- Implement Dijkstra's algorithm using heapq
- Return shortest distances from a source node to all reachable nodes
- Reconstruct the shortest path using a predecessors dict
Dijkstra's algorithm extends the relaxation idea from the previous lesson into a complete algorithm. The key guarantee: always relax from the node with the currently smallest known distance. A min-heap (priority queue) enforces that ordering efficiently.
The algorithm
- Initialise
dist[source] = 0,dist[v] = ∞for all other nodes. - Push
(0, source)onto a min-heap. - Pop the cheapest
(d, u). Ifd > dist[u], this is a stale entry — skip it. - For each neighbour
(v, w)ofu, relax: ifdist[u] + w < dist[v], updatedist[v]and push(dist[v], v)onto the heap. - Repeat until the heap is empty.
The "stale entry" check replaces the need to update existing heap entries (which is expensive). Push a new entry instead; when you pop the stale one, discard it.
Implementation
Complexity
| Operation | Cost |
|---|---|
| Each node popped from heap | O(log V) |
| Each edge relaxed | O(log V) for the push |
| Total | O((V + E) log V) |
This beats Bellman-Ford's O(VE) whenever the graph is sparse (E is not much larger than V).
Dijkstra's requires all edge weights to be non-negative. A single negative edge can cause it to miss the true shortest path because it commits to a "cheapest so far" without expecting prices to drop further. For negative weights, use Bellman-Ford instead.
Reconstructing the path
The pred dict records, for each node, which node we came from on the cheapest
known path. To recover the path to a target, walk backwards through pred
until you reach None (the source has no predecessor), then reverse.
If pred[target] is still None and target != source, the node is
unreachable — return an empty list.
Where to go next
Next: topological sort — ordering nodes in a directed acyclic graph so every edge points "forward." A key tool for build systems, course prerequisites, and any domain with dependency ordering.
Weighted graphs
Extend adjacency lists to hold edge weights, see why BFS breaks on weighted graphs, and learn the relaxation principle behind Dijkstra's algorithm.
Topological sort
Understand topological order in a DAG, learn Kahn's algorithm and DFS-based post-order, and see why cycles make it impossible.