Skip to content

Shortest paths with Dijkstra

Working knowledgeUnder the hoodYou should know: heaps

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.

The example graph before the search, with each edge's cost
Road graph · edge label = cost
4121583
Sd ∞
Ad ∞
Bd ∞
Cd ∞
Dd ∞
  • 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.

BFS · fewest edgesS → B → D = 9Two edges, the first route BFS reaches, and 2 more than it needs to be.
Dijkstra · lowest total costS → B → A → C → D = 7Four edges, but each is cheap. Finding it means tracking cost, not edge count.

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.

Dijkstra from S
Step 1 of 10
Road graph · edge label = cost
4121583
Sd ∞
Ad ∞
Bd ∞
Cd ∞
Dd ∞
Heap · heapq list, min at topEmpty
Settled · final distance
Empty
  • 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.

0 of 5 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.

dijkstra.py
import heapq
def dijkstra(graph, start):
dist = {start: 0}
heap = [(0, start)]
done = set()
while heap:
d, node = heapq.heappop(heap)
if node in done:
continue # stale entry: already settled
done.add(node) # d is now final
for nxt, w in graph[node]:
nd = d + w
if nd < dist.get(nxt, float("inf")):
dist[nxt] = nd # a shorter way in
heapq.heappush(heap, (nd, nxt))
Text
{'S': 0, 'A': 3, 'B': 1, 'C': 4, 'D': 7}

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.

What the code above returns when one edge is negative
Graph with B → A costing −2
12-21
Sd 0
Ad 0
Bd 2
Cd 2 ✗
  • 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

Single-source shortest paths, V nodes and E edges
AlgorithmEdge costsTime
BFSAll equalO(V + E)
Dijkstra with a binary heap0 or moreO((V + E) log V)
Bellman-FordAny, with negative-cycle detectionO(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.

08 Check yourself

Question

The heap holds (5, X), (7, Y) and (6, X). X is already settled at 5. What happens when (6, X) comes out?

Question

Every edge in a graph costs exactly 1. What does Dijkstra's algorithm give you?

Question

Why is a node's distance final the moment it is popped?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?