A levels Computer Science · Algorithms
Dijkstra's shortest path
1The shortest path problem
Given a weighted graph, find the route between two vertices with the lowest total weight (distance, time or cost). This is the problem sat-navs and network routers solve.
Dijkstra's algorithm finds the shortest path from one start vertex to every other vertex, as long as no edge has a negative weight.
Check yourself
What kind of graph does Dijkstra's algorithm work on?
Show the answer
A weighted graph with no negative edge weights
Non-negative weights.
2The algorithm
- Give the start vertex a distance of 0 and every other vertex infinity.
- Pick the unvisited vertex with the smallest distance and mark it visited.
- For each unvisited neighbour, calculate distance via this vertex. If it is smaller than the neighbour's current distance, update it and record this vertex as its previous vertex.
- Repeat steps 2 and 3 until every vertex is visited (or the target is visited).
- Follow the previous vertices back from the target to get the route.
Once a vertex is visited, its distance is final: no shorter route to it can be found later.
Check yourself
Which vertex is visited next in Dijkstra's algorithm?
Show the answer
The unvisited vertex with the smallest current distance
Greedy choice.
3A worked trace
Final shortest distances from A. The red edges form the shortest-path tree; note that B is reached more cheaply through C (3) than directly (4).
Dijkstra from A
- Start: A = 0, the rest ∞. Visit A: C = 2, B = 4.
- Smallest unvisited is C (2). Visit C: B via C = 2 + 1 = 3 < 4, so B = 3 (previous C). D via C = 2 + 8 = 10.
- Visit B (3): D via B = 3 + 5 = 8 < 10, so D = 8 (previous B).
- Visit D (8): E = 8 + 3 = 11.
- Visit E (11). Route to E: E ← D ← B ← C ← A, so A → C → B → D → E, length 11.
| Step | A | B | C | D | E | Visited |
|---|---|---|---|---|---|---|
| 1 | 0 | 4 | 2 | ∞ | ∞ | A |
| 2 | 0 | 3 | 2 | 10 | ∞ | A, C |
| 3 | 0 | 3 | 2 | 8 | ∞ | A, C, B |
| 4 | 0 | 3 | 2 | 8 | 11 | A, C, B, D |
Check yourself
In the trace, why does B's distance change from 4 to 3?
Show the answer
The route A → C → B (2 + 1) is shorter than the direct edge (4)
Relaxing the edge.
4Implementing with a priority queue
A priority queue keeps the unvisited vertices ordered by distance, so the smallest is always removed first.
import heapq
def dijkstra(graph, start):
dist = {v: float("inf") for v in graph}
dist[start] = 0
pq = [(0, start)]
while pq:
d, v = heapq.heappop(pq)
if d > dist[v]:
continue # an old, longer entry
for n, w in graph[v]:
if d + w < dist[n]:
dist[n] = d + w
heapq.heappush(pq, (dist[n], n))
return dist
With a priority queue (a binary heap), Dijkstra runs in O((V + E) log V). With a simple list, finding the smallest each time makes it O(V²).
Check yourself
What does the priority queue do in Dijkstra's algorithm?
Show the answer
Always gives the unvisited vertex with the smallest distance
Smallest first.
5The A* algorithm
A* is a faster version for finding a route to one target. It adds a heuristic h(v), an estimate of the distance left (for example the straight-line distance on a map):
$$f(v) = g(v) + h(v)$$
where g(v) is the distance so far. A* visits the vertex with the smallest f, so it heads towards the target instead of spreading out in every direction.
- If the heuristic never overestimates the real distance, A* still finds the shortest path.
- A* is used in games (route-finding for characters) and sat-navs.
Check yourself
What does the heuristic in A* estimate?
Show the answer
The remaining distance from a vertex to the target
Guess of what is left.
6Uses and limits
Uses of shortest-path algorithms:
- sat-nav and map route planning;
- network routing protocols (such as OSPF) that send data packets along the cheapest path;
- planning delivery routes and flight connections.
Limits:
- Dijkstra gives wrong answers if edges have negative weights.
- On huge graphs, such as a whole country's roads, it may be too slow without a heuristic (A*) or pre-processing.
Check yourself
Why can Dijkstra fail with negative edge weights?
Show the answer
A visited vertex's distance is treated as final, but a negative edge could make it shorter later
Final too early.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera