Dijkstra's algorithm
Shortest path from a source vertex to every other vertex.
Setup. A weighted graph with NON-NEGATIVE edge weights. Find the shortest distance from a chosen source to every other vertex.
Edexcel labelling convention. Each vertex has THREE boxes:
- Order of permanent assignment (1, 2, 3, ...).
- Permanent label (final shortest distance from ).
- Working labels (tentative distances, written below, with replaced ones struck through).
Procedure.
- Assign permanent label to the source ; order .
- Update working labels at each NEIGHBOUR of : label of + edge weight.
- Find the UNVISITED vertex with the SMALLEST current working label; assign it a permanent label equal to its working label; record the order.
- Update working labels at the neighbours of the newly permanent vertex: new label = . Strike through replaced labels.
- Repeat 3-4 until every vertex has a permanent label.
Reading off the path. Once Dijkstra terminates, the permanent label at the destination is the shortest distance. To recover the path, work BACKWARDS from : at each vertex in the path, the predecessor satisfies
Worked example (recap from topical).
Network: . Source .
| Vertex | Order | Permanent | Working (left → right) |
|---|---|---|---|
| 1 | 0 | — | |
| 3 | 5 | ||
| 2 | 2 | ||
| 4 | 8 | ||
| 5 | 11 |
Trace path from : so ; or so . Both shortest. From : so direct. Path (or ).
Why non-negative weights matter. Dijkstra assumes a permanent label is final. If negative weights are allowed, a longer-looking detour could become shorter through a negative edge — Dijkstra fails. (For graphs with negative weights, use Bellman-Ford — NOT on the D1 syllabus.)
- Source has permanent label .
- Smallest unvisited working label gets the next permanent label.
- Update neighbours by min(current, new).
- Strike through replaced labels — never erase.
- Trace path backwards using .