Edexcel International Advanced Level Computer Science, point 15.2.3
Definition
A shortest path algorithm finds the route between vertices of a weighted graph (14.1.3) with the smallest total weight (distance, time or cost). Two are required: Dijkstra's algorithm and the A* algorithm.
Function and why needed
Used in satnav and maps, network routing (12.1.3), game characters finding their way, robot navigation and flight planning.
The graph used in the examples (undirected, weighted):
Edge list: A-B 4, A-C 2, B-D 5, C-D 8, C-E 10, D-E 2, D-F 6, E-F 3.
graph = {
"A": {"B": 4, "C": 2},
"B": {"A": 4, "D": 5},
"C": {"A": 2, "D": 8, "E": 10},
"D": {"B": 5, "C": 8, "E": 2, "F": 6},
"E": {"C": 10, "D": 2, "F": 3},
"F": {"D": 6, "E": 3},
}
a. Dijkstra's algorithm
Definition and characteristics
Dijkstra's algorithm finds the shortest path from one start vertex to every other vertex in a graph with non-negative edge weights. It is greedy (15.1.1): it always settles the unvisited vertex with the smallest known distance next, which is guaranteed to be final.
Operation
- Give the start vertex distance 0, and all others infinity (∞).
- Mark all vertices unvisited.
- Pick the unvisited vertex with the smallest distance (the current vertex). Mark it visited.
- For each unvisited neighbour, calculate current distance + edge weight. If it is smaller than the neighbour's recorded distance, update it and record the current vertex as its previous vertex.
- Repeat from step 3 until all vertices are visited (or the target is visited).
- Read off the shortest path by following the previous vertices back from the target.
Hand trace from A
| Step | Visit | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|
| Start | 0 | ∞ | ∞ | ∞ | ∞ | ∞ | |
| 1 | A (0) | 0 | 4 | 2 | ∞ | ∞ | ∞ |
| 2 | C (2) | 0 | 4 | 2 | 10 | 12 | ∞ |
| 3 | B (4) | 0 | 4 | 2 | 9 | 12 | ∞ |
| 4 | D (9) | 0 | 4 | 2 | 9 | 11 | 15 |
| 5 | E (11) | 0 | 4 | 2 | 9 | 11 | 14 |
| 6 | F (14) | 0 | 4 | 2 | 9 | 11 | 14 |
- Step 2 (visiting C): D = 2 + 8 = 10, E = 2 + 10 = 12.
- Step 3 (visiting B): D = 4 + 5 = 9, which is better than 10, so it's updated.
- Step 4 (visiting D): E = 9 + 2 = 11 (better than 12), F = 9 + 6 = 15.
- Step 5 (visiting E): F = 11 + 3 = 14 (better than 15).
Shortest distance from A to F = 14. Previous vertices: F from E, E from D, D from B, B from A. Path: A, B, D, E, F.
Code
def dijkstra(graph, start):
dist = {v: float("inf") for v in graph}
prev = {v: None for v in graph}
dist[start] = 0
unvisited = set(graph)
while unvisited:
current = min(unvisited, key=lambda v: dist[v])
unvisited.remove(current)
for neighbour, weight in graph[current].items():
new = dist[current] + weight
if new < dist[neighbour]:
dist[neighbour] = new
prev[neighbour] = current
return dist, prev
def path_to(prev, target):
path = []
while target is not None:
path.append(target)
target = prev[target]
return path[::-1]
dist, prev = dijkstra(graph, "A")
print(dist["F"], path_to(prev, "F")) # 14 ['A', 'B', 'D', 'E', 'F']
Efficiency
- With a simple list: . With a priority queue (heap): .
Benefits and drawbacks
- Benefits: guaranteed to find the shortest path (for non-negative weights), and gives the shortest paths to all vertices at once.
- Drawbacks: explores in every direction (including away from the goal), so it can be slow on large graphs when you need just one destination, and it fails with negative weights.
b. The A* algorithm
Definition and characteristics
A* ("A-star") finds the shortest path from a start vertex to a single goal vertex, and is an improvement on Dijkstra's that uses a heuristic to head towards the goal. It chooses the next vertex using
- : the actual cost so far from the start to .
- : a heuristic estimate of the cost from to the goal (for example straight-line distance on a map).
- : the estimated total cost of a path through .
It always expands the vertex with the lowest . If never overestimates the true cost (it is admissible), A* is guaranteed to find the shortest path. With , A* is Dijkstra's algorithm.
Operation
- Put the start vertex in the open list, with and .
- Take the vertex with the lowest from the open list.
- If it is the goal, stop, and trace back the path.
- Otherwise, for each neighbour: calculate through this vertex and . If the neighbour is new, or this route is better, update it and add it to the open list.
- Move the current vertex to the closed list. Go back to step 2.
Hand trace: A to F
Heuristic estimates of the distance to F (never more than the true distance): h(A) = 10, h(B) = 9, h(C) = 9, h(D) = 5, h(E) = 3, h(F) = 0.
| Step | Expand (lowest ) | Neighbours updated: , | Open list after |
|---|---|---|---|
| 1 | A ( = 10) | B: 4, 13. C: 2, 11 | C 11, B 13 |
| 2 | C (11) | D: 10, 15. E: 12, 15 | B 13, D 15, E 15 |
| 3 | B (13) | D: 9, 14 (better) | D 14, E 15 |
| 4 | D (14) | E: 11, 14 (better). F: 15, 15 | E 14, F 15 |
| 5 | E (14) | F: 14, 14 (better) | F 14 |
| 6 | F (14) | Goal reached: stop |
Shortest path: A, B, D, E, F, with cost 14, the same as Dijkstra's. A* stopped as soon as it reached F, and didn't need to finish exploring every vertex.
Code
import heapq
def a_star(graph, start, goal, h):
open_list = [(h[start], 0, start)] # (f, g, vertex)
best_g = {start: 0}
prev = {start: None}
while open_list:
f, g, current = heapq.heappop(open_list)
if current == goal:
path = []
while current is not None:
path.append(current)
current = prev[current]
return g, path[::-1]
for neighbour, weight in graph[current].items():
new_g = g + weight
if new_g < best_g.get(neighbour, float("inf")):
best_g[neighbour] = new_g
prev[neighbour] = current
heapq.heappush(open_list,
(new_g + h[neighbour], new_g, neighbour))
return None
h = {"A": 10, "B": 9, "C": 9, "D": 5, "E": 3, "F": 0}
print(a_star(graph, "A", "F", h)) # (14, ['A', 'B', 'D', 'E', 'F'])
The heuristic
- Admissible: never overestimates the true cost, so the result is the shortest path.
- A better (closer) heuristic expands fewer vertices. A poor one () makes it slower, like Dijkstra's. An overestimating one can give a non-optimal path.
- Examples: straight-line (Euclidean) distance for maps, and Manhattan distance (|dx| + |dy|) for grid movement.
Benefits and drawbacks
- Benefits: usually much faster than Dijkstra's for a single goal, as it focuses on the direction of the goal, and still finds the shortest path with an admissible heuristic.
- Drawbacks: needs a good heuristic (domain knowledge), uses more memory (the open and closed lists), and performance depends on the heuristic's quality.
Comparison
| Dijkstra's | A* | |
|---|---|---|
| Finds | Shortest paths from the start to all vertices | Shortest path from the start to one goal |
| Chooses next vertex by | Lowest (cost so far) | Lowest |
| Uses a heuristic? | No | Yes |
| Explores | Evenly in all directions | Towards the goal |
| Speed for one goal | Slower | Usually faster |
| Guaranteed shortest? | Yes | Yes, if is admissible |
| Best for | Many destinations, no heuristic available | One goal, with a good heuristic (maps, games) |
Worked example
Task: use Dijkstra's algorithm on the graph with edges P-Q 3, P-R 6, Q-R 2, Q-S 7, R-S 3 to find the shortest path from P to S.
| Step | Visit | P | Q | R | S |
|---|---|---|---|---|---|
| Start | 0 | ∞ | ∞ | ∞ | |
| 1 | P | 0 | 3 | 6 | ∞ |
| 2 | Q (3) | 0 | 3 | 5 | 10 |
| 3 | R (5) | 0 | 3 | 5 | 8 |
| 4 | S (8) | 0 | 3 | 5 | 8 |
- At Q: R = 3 + 2 = 5 (better than 6), S = 3 + 7 = 10.
- At R: S = 5 + 3 = 8 (better than 10).
Shortest distance P to S = 8, by P, Q, R, S (previous: S from R, R from Q, Q from P). Not the direct-looking P-R-S (9), nor P-Q-S (10).
Exam tip: trace Dijkstra's with a table of distances, marking the vertex you visit and only updating when a new distance is smaller. Write the path by following previous vertices back. For A*, show , and = + at each step. State why A* is faster (the heuristic guides it), and the condition (admissible heuristic).
Check yourself
What does Dijkstra's algorithm find?
The shortest path from a start vertex to every other vertex in a weighted graph with non-negative weights.
In A*, what do g, h and f stand for?
g is the actual cost from the start, h is the heuristic estimate to the goal, and f = g + h is the estimated total cost through that vertex.
Why is A* usually faster than Dijkstra's for a single destination?
Its heuristic guides the search towards the goal, so it explores fewer vertices.
What is an admissible heuristic?
One that never overestimates the true cost to the goal; it guarantees that A* finds the shortest path.
What happens to A* if the heuristic is always 0?
It behaves like Dijkstra's algorithm.