Algorithms / Dijkstra’s shortest path

Dijkstra’s shortest path

Always expand the cheapest place you can reach, and never look back once it is settled. Six nodes, nine roads, one greedy idea.

Intermediate7 steps~6 min
Start — where every journey begins, at cost 0
Frontier — reached, but maybe not by the best road yet
Settled — its shortest distance is final
// THE SHORT VERSION

In 30 seconds

Dijkstra’s algorithm finds the cheapest route from one node to every other node of a graph, as long as no edge has a negative cost.

It keeps a tentative cost for each node, repeatedly settles the cheapest node not yet settled, and checks whether going through it makes any neighbour cheaper.

Once a node is settled its cost is final: every other way to reach it would pass through something that already costs at least as much.

Dijkstra’s shortest path, step by step

STEPS01 / 07

The frontier is usually a min-heap, giving O((V + E) log V). Negative road costs break the “settled is final” promise.

STEP 01 / 07 The map
THE MATH
G = (V, E) V = {A, B, C, D, E, F} start = A, goal = F all weights ≥ 0
  1. Step 1: The map. Six places joined by roads, each road with a cost. We want the cheapest way from A to F. Dijkstra needs every cost to be zero or more.
  2. Step 2: Start at zero. We know only one thing for sure: getting to A from A costs nothing. Every other place starts at “infinitely far” until we find a road there.
  3. Step 3: Settle A, relax its roads. Take the cheapest node off the frontier — A — and call it settled. Then “relax” each road out of it: if going through A is cheaper than what we knew, update.
  4. Step 4: Settle C, find a shortcut. C is now the cheapest on the frontier. Going A → C → B costs 3, beating the direct road’s 4, so B’s distance drops. This is why we never settle early.
  5. Step 5: Settle B. B comes off the frontier at 3. Its road to D makes D cheaper again: 8 instead of 10. The blue edges always show the best known way in.
  6. Step 6: Settle D, then E. D opens roads to E and F. Then E, now at 10, turns out to be a better way into F than D’s direct road: 13 beats 14.
  7. Step 7: Reach the goal. When the goal is settled its distance is final. Walk the blue predecessor edges backwards from F and you get the route: five roads, total cost 13.
VALUES SO FAR
dist A····start
dist C····settled
dist B····settled
dist D····settled
dist E····settled
dist F····goal
path····route
// AFTER

Learn next

Nothing builds on this one yet. See every algorithms concept.

Spotted a mistake on this page?