Shortest paths with Dijkstra
BFS finds the route with the fewest edges, but when edges have costs, the cheapest route can have more of them. Dijkstra's algorithm always settles the closest unsettled node next, and a heap makes finding that node cheap.
01 When fewest edges is not cheapest
Breadth-first search finds the route with the fewest edges. That is the shortest path only when every edge costs the same. Roads take different times, links have different latencies, and then two short hops can beat one long one.
- not reached
Arrows are one-way. Fewest edges to D: S → B → D, 2 edges costing 9. Cheapest: S → B → A → C → D, 4 edges costing 7.
02 Settle the closest unsettled node
Dijkstra's algorithm keeps a tentative distance for each node: the cheapest route found so far, starting at ∞. Looking at an edge u → v with cost w and asking "is dist[u] + w better than dist[v]?" is called relaxing the edge.
The rule is: of all the nodes not yet settled, take the one with the smallest tentative distance, declare it final (settle it), and relax its edges. Repeat until none are left.
Why is it safe to call that distance final? Any other route to that node has to leave the settled region somewhere, through a node whose tentative distance is at least as big, and then add edges that cost 0 or more. It cannot come in cheaper. That argument needs every edge cost to be non-negative; keep that in mind for later.
Finding "the smallest tentative distance" over and over is exactly what a min-heap is for. Push (distance, node) pairs and pop the smallest.
03 Dijkstra, step by step
Same graph. Each node's tag is its tentative distance. The heap panel shows Python's real heapq list: the array, and the tree it stands for. The smallest entry always sits at index 0, but the rest are only partly ordered.
- not reached
- tentative, in the heap
- settled this step
- settled
- just pushed
- stale heap entry
Every distance is unknown, written ∞. The heap is empty and nothing is settled.
Nodes were settled in order of distance: 0, 1, 3, 4, 7. That ordering is the whole idea. Note that A was first reached for 4 and later improved to 3 before it was settled; tentative distances can drop until the moment a node is popped.
04 The code
The loop is the trace: pop, skip if stale, settle, relax. The done set is what makes a stale entry recognisable.
That is the real output of python3 dijkstra.py on Python 3.14. Python's heapq has no decrease-key, so improving a distance pushes a new entry and the old one becomes stale. The heap can hold one entry per relaxation, up to E entries, which still gives O(E log E) = O(E log V) time.
If you only need the distance to one target, return as soon as that target is popped and settled. Everything after that is about other nodes.
05 Why negative edges break it
The safety argument said a route cannot get cheaper by going further. A negative edge makes exactly that possible, so a settled distance can turn out to be wrong after the fact, and everything relaxed from it inherits the error.
- wrong distance
- settled
A was settled at 1 and passed 1 + 1 = 2 on to C. Then B found a route to A costing 2 − 2 = 0, too late: A was already done, so C keeps 2 instead of the true 1. Real output: {'S': 0, 'A': 0, 'B': 2, 'C': 2}.
Dijkstra's algorithm assumes every edge cost is 0 or more. With negative costs use Bellman-Ford, which relaxes every edge V − 1 times (O(V · E)) and can also detect a negative cycle. Some Dijkstra variants re-process nodes when their distance drops, but then the running time is no longer guaranteed.
06 What it costs, and what it can do
| Algorithm | Edge costs | Time |
|---|---|---|
| BFS | All equal | O(V + E) |
| Dijkstra with a binary heap | 0 or more | O((V + E) log V) |
| Bellman-Ford | Any, with negative-cycle detection | O(V · E) |
Dijkstra works for any path cost that never goes down as the path grows, not just sums. In Path With Minimum Effort, a path's cost is the largest step on it. Replace d + w with max(d, w) and the same loop finds the path with the smallest largest step.
Road maps have millions of nodes, so routing services typically do not run plain Dijkstra per query. They add a goal-directed estimate (A* search) or precompute shortcuts (for example contraction hierarchies), and the core is still a priority queue settling the closest node next.
07 When it bites
done.add(nxt) # when pushingSettling on push instead of on popA node pushed first is not necessarily reached cheapest: A was pushed at 4 and finished at 3. Mark a node final only when it comes off the heap.heappush(heap, (node, d))Putting the node first in the tupleThe heap orders tuples by their first field, so this pops nodes alphabetically. The distance must come first.if node in done: continueDropping the stale checkWithout it, a stale entry relaxes its edges again with an old, bigger distance. The answer stays right, because nothing improves, but the work can grow a lot on dense graphs.graph["B"].append(("A", -2))Negative edgesNo error is raised; the distances are just wrong, as shown above. Check costs, or use Bellman-Ford.if nd < dist[nxt]:Unreached nodesA plain lookup raises KeyError the first time a node is seen. Use dist.get(nxt, float("inf")) so a node seen for the first time counts as infinitely far. A node never reached is missing from the result: decide whether that means "unreachable" or an error.