CIE AS & A Level Computer Science, section 18.1 (Artificial Intelligence)
Graphs
A graph is made of nodes (vertices) joined by edges. In a weighted graph each edge has a cost, such as distance or time. Graphs model road maps, networks and puzzles. The shortest path problem is to find the lowest total cost route between two nodes.
Dijkstra's algorithm
Finds the shortest path from one start node to every other node.
- Give the start node a distance 0 and every other node infinity.
- Take the unvisited node with the smallest distance. Mark it as visited.
- For each neighbour, work out the distance through this node. If it is smaller, update it (and record the node it came from).
- Repeat until all nodes are visited (or the target is reached).
Worked example
Edges: A-B 4, A-C 2, B-C 1, B-D 5, C-D 8, C-E 10, D-E 2.
| Step | Visit | A | B | C | D | E |
|---|---|---|---|---|---|---|
| Start | 0 | inf | inf | inf | inf | |
| 1 | A | 0 | 4 | 2 | inf | inf |
| 2 | C | 0 | 3 | 2 | 10 | 12 |
| 3 | B | 0 | 3 | 2 | 8 | 12 |
| 4 | D | 0 | 3 | 2 | 8 | 10 |
| 5 | E | 0 | 3 | 2 | 8 | 10 |
The shortest path from A to E has length 10: A, C, B, D, E.
A* algorithm
A* finds the shortest path to one target, and is faster because it is guided by a heuristic, , an estimate of the remaining cost to the target (for example straight-line distance).
- is the actual cost from the start to node .
- is the estimated cost from to the target.
It always expands the node with the lowest . If never overestimates, A* finds the shortest path.
| Dijkstra | A* | |
|---|---|---|
| Finds | shortest paths to all nodes | shortest path to one target |
| Uses | only the cost so far, | cost so far plus heuristic, |
| Speed | explores in all directions | explores fewer nodes |
Common mistake: in Dijkstra's algorithm, forgetting to update a distance when a shorter route is found through a newly visited node. Also, A* with an overestimating heuristic may not give the shortest path.
Exam tip: show a table with a column for each node and a row for each step, and state the final path by following the nodes back, not just its length.
Check yourself
What does the heuristic in A* estimate?
The remaining cost from a node to the target.
What is the first node visited in Dijkstra’s algorithm?
The start node, which has distance 0.
Why is A* usually faster than Dijkstra’s algorithm?
The heuristic guides the search towards the target, so fewer nodes are explored.