Dijkstra’s algorithm step by step
Settle the closest node, then relax its neighbours.
The idea
Dijkstra’s algorithm finds the shortest distance from one start node to every other node in a graph whose edge weights are not negative. Exam questions give you an edge list and ask for the shortest path length, or for the order nodes are settled.
The method
- Give the start node distance 0 and every other node ∞.
- Repeatedly pick the unsettled node with the smallest known distance and settle it. Its distance is now final.
- For each neighbour, check whether going through the settled node is shorter. If so, update it.
- Stop when every node you care about is settled.
Worked example
Edges: A–B (4), A–C (2), C–B (1), B–D (5), C–D (8), D–E (3). What is the shortest distance from A to E?
| Step | Settle | A | B | C | D | E |
|---|---|---|---|---|---|---|
| 1 | A (0) | 0 | 4 | 2 | ∞ | ∞ |
| 2 | C (2) | 0 | 3 | 2 | 10 | ∞ |
| 3 | B (3) | 0 | 3 | 2 | 8 | ∞ |
| 4 | D (8) | 0 | 3 | 2 | 8 | 11 |
| 5 | E (11) | 0 | 3 | 2 | 8 | 11 |
Settle order: A, C, B, D, E. The best route is A → C → B → D → E.
Answer: 2 + 1 + 5 + 3 = 11
Common mistakes
- Stopping when you first see the target instead of when you settle it.
- Forgetting that a longer-looking path can be cheaper (A→C→B beats A→B here).
- Using Dijkstra with negative weights, where it can give wrong answers.
Practise this topic
Try questions on this topic with instant explanations, or test yourself against the world in the ranked exam.