A Level Computer Science · Chapter 26 · Component 02: Algorithms and programming
Every satnav, social network and game map is a graph, and a handful of algorithms find their way around it, from visiting every node to finding the shortest route.
This chapter teaches the two ways to traverse a graph, breadth-first and depth-first, and the two classic shortest-path algorithms, Dijkstra's algorithm and A*. You will trace each by hand, explain why it works, and choose between them.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- represent a graph as an adjacency list or an adjacency matrix, weighted or unweighted
- trace a breadth-first traversal, using a queue, and explain why it finds routes with the fewest edges
- trace a depth-first traversal, using recursion or a stack, and describe its uses
- trace Dijkstra's algorithm with a table of distances, and recover the shortest path
- explain why Dijkstra's algorithm needs non-negative weights, and state its complexity
- trace A* search with a heuristic, and explain what makes a heuristic admissible
- choose a suitable algorithm for a given graph problem, and justify the choice
Time: three sessions, about 4 hours, plus the programming task.
You need first: queues and stacks from Arrays, records, stacks and queues, graphs from Linked lists, hash tables, graphs and trees, and recursion from Subroutines and recursion.
The big picture
The big picture
In 1956, a young Dutch programmer named Edsger Dijkstra sat in a café in Amsterdam with his fiancée. He wanted to show off a new computer, and needed a problem that non-scientists could understand. He chose the shortest route between two Dutch cities, and designed an algorithm for it in about twenty minutes, without pen or paper.
That algorithm now runs billions of times a day. Satnavs and map apps use versions of it to plan routes. Internet routers use it to send data along the fastest path. Games use a refinement of it, called A*, to move characters around obstacles.
All of these problems share one structure: a graph. A graph is a set of nodes, also called vertices, joined by edges. The nodes might be towns, routers, people or squares on a game board. The edges might be roads, cables, friendships or legal moves.
Look at the graph above and try to find the shortest route from A to E. The road from A to B is the shortest first step, so it is tempting to start there. But every route through B is long. The best route goes A, C, D, E, with a total of 7.
Graphs are also how computers think about connections they cannot see. A search engine treats the web as a graph of pages joined by links. A navigation app treats a city as a graph of junctions joined by roads, with each road weighted by its current travel time.
This is the heart of the problem. A route that looks good at the start can turn out badly, so a good algorithm must keep its options open. Dijkstra's algorithm does exactly that, by always extending the closest known node rather than the closest next step.
Some problems do not need the shortest route, only a way to visit everything. A web crawler must reach every page linked from a starting page. A program solving a maze must explore until it finds the exit. These are traversals, and there are two standard kinds: breadth-first and depth-first.
The difference between the two is the data structure behind them. Breadth-first search uses a queue, so it explores level by level, like a ripple spreading out. Depth-first search uses a stack, or recursion, so it follows one path as far as it can before turning back.
By the end of this chapter you will be able to run all four algorithms by hand on any small graph. That skill is tested directly in exams, where you complete a trace table or state the order nodes are visited.
Section 1
Graphs and their representation
Graph vocabulary
A graph has nodes and edges. In an undirected graph, an edge can be travelled both ways, like a two-way road. In a directed graph, each edge has a direction, like a one-way street. A weighted graph gives each edge a number, such as a distance, a time or a cost.
Two nodes joined by an edge are neighbours, or adjacent. A path is a sequence of nodes, each joined to the next. A cycle is a path that returns to where it started. A graph is connected if there is a path between every pair of nodes.
Adjacency lists
An adjacency list stores, for each node, a list of its neighbours, with the weights if the graph is weighted. It is compact, because it stores only the edges that exist. Most real graphs, such as road maps, have far fewer edges than possible, so adjacency lists are the usual choice.
Worked example 1: an adjacency list
Write the adjacency list entries for nodes A and D of the road network, in alphabetical order.
| Working | Reason |
|---|---|
| A is joined to B (1) and C (4) | Read the edges that touch A |
| A: B 1, C 4 | List each neighbour with its weight |
| D is joined to B (7), C (1) and E (2) | The graph is undirected, so B–D counts for D too |
| D: B 7, C 1, E 2 | Neighbours are kept in alphabetical order |
Adjacency matrices
An adjacency matrix is a grid with one row and one column for each node. The entry in row i, column j is the weight of the edge from i to j, or a blank or ∞ if there is none. For an undirected graph the matrix is symmetric about its diagonal.
A matrix makes it instant to check whether two nodes are joined, because it is a single lookup. But it uses space for every possible edge: n nodes need n² entries, even if most are empty. It suits small graphs, or graphs where most pairs are joined.
Worked example 2: choosing a representation
A map has 10,000 junctions, and each junction joins about 4 roads. Compare the storage of an adjacency matrix and an adjacency list.
| Working | Reason |
|---|---|
| Matrix: 10,000 × 10,000 = 100,000,000 entries | One entry for every ordered pair of nodes |
| Edges: about 10,000 × 4 ÷ 2 = 20,000 roads | Each road is counted from both ends |
| List: about 2 × 20,000 = 40,000 neighbour entries | Each undirected edge appears in two lists |
| The list needs about 2,500 times less space | The graph is sparse, so a list is far better |
Common mistake: choosing an adjacency matrix for a sparse graph. A matrix stores an entry for every pair of nodes, so its size grows as n² whatever the number of edges. For a road map, with few roads per junction, almost all of it is empty. Use an adjacency list.
Graphs everywhere
Many problems become graph problems once you choose the nodes and edges. In a social network the nodes are people and the edges are friendships. In a timetable the nodes are lessons, and an edge joins two lessons that share a student, so they cannot run at the same time.
In a game of noughts and crosses, each node is a board position and each edge is a legal move. Searching this graph tells a computer which moves win. The skill is in the modelling: once a problem is a graph, the algorithms in this chapter can solve it.
Storing weights
In an adjacency list, each entry holds a neighbour and the weight of the edge to it, such as (B, 7). In a matrix, the weight is stored in the cell itself. An empty cell, or the value ∞, means there is no edge. A weight of 0 would mean a free edge, which is different from no edge at all.
For a directed graph, an edge from P to Q appears only in P's list, or only in row P of the matrix. The matrix is then no longer symmetric. One-way streets and links from one web page to another are directed.
Alphabetical order
In exams, and in this chapter, neighbours are taken in alphabetical order unless a question says otherwise. The algorithms do not need this, but it makes every trace come out the same way. Real programs take neighbours in whatever order they are stored.
Check yourself. Why is an adjacency matrix for an undirected graph symmetric?
Show the answer
In an undirected graph, an edge from i to j is also an edge from j to i, with the same weight. So the entry in row i, column j always equals the entry in row j, column i.
Section 2
Breadth-first search
The idea
Breadth-first search, or BFS, visits the start node, then every node one edge away, then every node two edges away, and so on. It explores the graph in layers, like a ripple spreading out from a stone dropped in a pond.
To keep track, it uses a queue. A queue is first in, first out, so nodes are visited in the order they were discovered. Each node is marked as discovered when it joins the queue, so that it is never added twice.
The algorithm
procedure bfs(graph, start)
queue = [start]
discovered = {start}
while queue is not empty
node = queue.dequeue()
visit(node)
for each neighbour of node, in order
if neighbour not in discovered then
discovered.add(neighbour)
queue.enqueue(neighbour)
endif
next neighbour
endwhile
endprocedure
Marking nodes when they are discovered, rather than when they are visited, matters. Otherwise a node with several neighbours already in the queue could be added several times, and visited more than once.
Common mistake: adding a node to the queue more than once. If a node is only marked when it is visited, it can be enqueued again by each neighbour that finds it first. Mark it as discovered as soon as it joins the queue.
Worked example 3: tracing breadth-first search
Trace a breadth-first traversal of the road network from A, ignoring the weights.
| Working | Reason |
|---|---|
| Visit A; enqueue B and C. Queue: B, C | A's neighbours in alphabetical order |
| Visit B; enqueue D and G. Queue: C, D, G | A is already discovered, so it is skipped |
| Visit C; enqueue F. Queue: D, G, F | D is already in the queue, so it is not added again |
| Visit D; enqueue E. Then visit G, F and E | No new nodes are found after E is added |
| Order: A, B, C, D, G, F, E | Every node one edge away comes before those two away |
Fewest edges
Because BFS explores in layers, the first time it reaches a node is along a path with the fewest edges. So BFS finds shortest paths in an unweighted graph, where every edge counts the same. In the road network, E is three edges from A.
But BFS ignores weights. The path with the fewest edges is not always the shortest in distance. From A, BFS reaches E by three edges, but the route A, B, G, E has length 13 while A, C, D, E has length 7.
Common mistake: using breadth-first search for shortest distances in a weighted graph. BFS finds the path with the fewest edges, not the smallest total weight. On a road map, a route with more but shorter roads can be quicker. Use Dijkstra's algorithm when edges have weights.
Worked example 4: fewest edges
Find the fewest number of roads from A to each town in the road network.
| Working | Reason |
|---|---|
| A is 0 roads from itself | The search starts at this node |
| B and C are 1 road away | They are A's neighbours, the first layer |
| D, G and F are 2 roads away | They are first reached from B or C |
| E is 3 roads away | It is first reached from D, in the third layer |
Breadth-first search as layers
It helps to picture BFS as drawing rings around the start. Ring 0 is the start itself. Ring 1 holds its neighbours, ring 2 their new neighbours, and so on. Every node lands in the ring equal to its fewest-edge distance from the start.
The queue keeps the rings in order. Nodes from ring 1 are all enqueued before any node from ring 2, because ring 2 nodes are only discovered when ring 1 nodes are visited. So the queue never mixes up the layers.
Cost of breadth-first search
Each node joins the queue once, and each edge is examined once from each end. So BFS takes time in proportion to the number of nodes plus the number of edges, O(n + e). Its memory is the queue, which can hold a whole layer at once.
Uses of breadth-first search
BFS finds the shortest number of moves in puzzles, such as the fewest moves to solve a sliding-tile puzzle. Social networks use it to find friends of friends, two edges away. Web crawlers often explore links breadth-first, so they find nearby pages before distant ones.
Check yourself. What data structure does breadth-first search use to hold the nodes waiting to be visited, and why?
Show the answer
It uses a queue. A queue is first in, first out, so nodes are visited in the order they were discovered, which makes the search spread out layer by layer.
Section 3
Depth-first search
The idea
Depth-first search, or DFS, goes as deep as it can before turning back. From the start node, it moves to an unvisited neighbour, then to an unvisited neighbour of that node, and so on. When it reaches a node with no unvisited neighbours, it backtracks to the last node that still has one.
Backtracking needs a memory of the route so far. Recursion provides it naturally, because each call returns to the one that made it. A program can also use an explicit stack, which is last in, first out.
The algorithm
procedure dfs(graph, node, visited)
visited.add(node)
visit(node)
for each neighbour of node, in order
if neighbour not in visited then
dfs(graph, neighbour, visited)
endif
next neighbour
endprocedure
Each call visits one node and then tries its neighbours in turn. The first unvisited neighbour starts a new call, which runs to completion before the next neighbour is tried. That is what makes the search go deep first.
Worked example 5: tracing depth-first search
Trace a recursive depth-first traversal of the road network from A.
| Working | Reason |
|---|---|
| Visit A, then its first neighbour B, then B's first unvisited neighbour D | Go deeper at every step |
| From D, B is visited, so go to C; from C, go to F; from F, go to E | Keep following the first unvisited neighbour |
| E's neighbours D and F are visited, so try G, which is unvisited | G is reached from E, deep in the search |
| G has nothing new; backtrack through E, F, C, D and B to A | Each call returns once its neighbours are done |
| Order: A, B, D, C, F, E, G | One long path before any backtracking |
Common mistake: visiting all of a node's neighbours before going deeper in depth-first search. That is breadth-first behaviour. In DFS, the first unvisited neighbour is explored completely, including its own neighbours, before the second neighbour is even looked at.
Figure 26.1 runs both traversals on the road network, one node at a time. Switch between them and compare the orders. Then turn on the wrong model, which assumes the two orders are the same.
Breadth-first and depth-first traversal
- Order so far
- A, B
- Breadth-first order
- A, B, C, D, G, F, E
- Depth-first order
- A, B, D, C, F, E, G
Breadth-first against depth-first
The two traversals visit the same nodes, but in different orders and with different costs. BFS holds a whole layer in its queue, which can be large on a wide graph. DFS holds only the current path, which can be long on a deep graph. Both take time O(n + e).
Choose by the problem. If the answer is likely to be close to the start, or you need the fewest edges, use BFS. If you must explore every possibility, or the answer is deep, use DFS. A maze solver can use either, but BFS finds the shortest way out.
Iterative depth-first search
With an explicit stack, DFS pushes the start node, then repeatedly pops a node, visits it if it is new, and pushes its unvisited neighbours. To match the recursive order, push the neighbours in reverse alphabetical order, so the first one is on top.
Worked example 6: depth-first from another start
Find the depth-first order of the road network starting from E.
| Working | Reason |
|---|---|
| Visit E; its first neighbour is D | E's neighbours are D, F and G |
| From D go to B, then from B go to A | Always take the first unvisited neighbour |
| From A, B is visited, so go to C; from C go to F | C's neighbour D is already visited |
| F, then C, then A have nothing new; backtrack to B, which still has G | G is the last unvisited node |
| Order: E, D, B, A, C, F, G | The start node changes the whole order |
Depth-first search and the call stack
Each recursive call to dfs is a frame on the call stack, holding the current node and the position reached in its loop of neighbours. When a call finishes, its frame is removed and the previous call continues from where it stopped. That is the backtracking.
The stack is as deep as the longest path the search follows. On the road network from A, it reaches seven frames deep, because the search runs through every node before backtracking. On a long chain of nodes, the depth could equal the number of nodes.
Detecting a cycle
DFS can tell whether a graph contains a cycle. Suppose the search, in an undirected graph, meets a visited node other than the one it has just come from. Then there is a second route back to that node, and that route closes a loop.
Cycle detection matters in practice. A spreadsheet must refuse a formula that depends on itself, and a build system must refuse tasks that each wait for the other. Both checks are depth-first searches looking for a cycle.
Uses of depth-first search
DFS suits problems that explore choices one at a time. Solving a maze is the classic case: follow a corridor to its end, then backtrack. DFS also detects cycles, finds connected components, and orders tasks that depend on one another.
It uses little memory on a wide graph, because it stores only the current path. But on a very deep graph, recursion can run out of stack space. And unlike BFS, the first path DFS finds to a node is not necessarily the shortest.
Check yourself. In depth-first search, what happens when the current node has no unvisited neighbours?
Show the answer
The search backtracks: the current call returns, and the previous node tries its next unvisited neighbour. If none remain there either, it backtracks further, until the search is complete.
Section 4
Dijkstra's algorithm
The idea
Dijkstra's algorithm finds the shortest distance from a start node to every other node in a weighted graph. It keeps a table of the best distance found so far to each node. At the start, the start node has distance 0 and every other node has distance infinity.
At each step, it picks the unvisited node with the smallest distance in the table and marks it as visited, or finalised. Its distance is now certain. Then it updates the table for that node's unvisited neighbours: if going through the new node gives a shorter distance, the table is changed.
The algorithm
procedure dijkstra(graph, start)
for each node: dist[node] = infinity, previous[node] = null
dist[start] = 0
while there are unvisited nodes with a finite distance
current = the unvisited node with the smallest dist
mark current as visited
for each unvisited neighbour of current
newDist = dist[current] + weight(current, neighbour)
if newDist < dist[neighbour] then
dist[neighbour] = newDist
previous[neighbour] = current
endif
next neighbour
endwhile
endprocedure
The previous table records the node each distance came through. When the algorithm finishes, following these links back from any node gives its shortest path, read in reverse.
Common mistake: finalising the neighbour with the cheapest edge rather than the smallest total distance. The next node to finalise is the one with the smallest distance from the start, not the one joined by the cheapest single edge. Choosing by edge weight is a greedy walk, and it can miss the best route.
Worked example 7: a full trace
Run Dijkstra's algorithm on the road network from A.
| Working | Reason |
|---|---|
| Finalise A (0); update B to 1 and C to 4 | A's neighbours are reached directly |
| Finalise B (1); update D to 1 + 7 = 8 and G to 1 + 3 = 4 | B has the smallest unvisited distance |
| Finalise C (4); update D to 4 + 1 = 5 and F to 4 + 6 = 10 | C beats G on the tie by alphabetical order |
| Finalise G (4), giving E 13; finalise D (5), improving E to 7 | Each step finalises the closest remaining node |
| Finalise E (7), improving F to 8; finally finalise F (8) | Every node now has its shortest distance |
The final distances are A 0, B 1, C 4, D 5, E 7, F 8 and G 4. Notice how D was first given distance 8, through B, and then improved to 5, through C. The algorithm keeps such options open until a node is finalised.
Laying out the trace table
In an exam, set out Dijkstra's algorithm as a table. Write one column for each node and one row for each step. In each row, record the node finalised and the current distance to every node. When a distance improves, write the new value and note the node it came through.
Some questions use a diagram instead, with boxes beside each node for its order of finalising, its final distance and its working values. The method is the same: finalise the smallest unvisited distance, update the neighbours, and repeat until every node is done.
Worked example 8: recovering the path
Use the previous-node links from worked example 7 to find the shortest path from A to F.
| Working | Reason |
|---|---|
| previous[F] = E, because F was last improved through E | F's best distance, 8, came via E |
| previous[E] = D and previous[D] = C | Follow the links back towards A |
| previous[C] = A, which is the start | Stop when the start node is reached |
| Reverse the list: A, C, D, E, F, with length 4 + 1 + 2 + 1 = 8 | The path is read from start to end |
Figure 26.2 runs Dijkstra's algorithm one node at a time, showing the distance table. Step through it and watch D's distance improve. Then switch on the wrong model, which always takes the cheapest road from the current node.
Dijkstra's algorithm and A*
- Finalised so far
- A
- Nodes finalised before E
- 6 (Dijkstra), 4 (A*)
- Shortest route
- A → C → D → E, length 7
Check yourself. In Dijkstra's algorithm, when is a node's distance known to be final?
Show the answer
A node's distance is final when it is picked as the unvisited node with the smallest distance. No later route can be shorter, because every other route must pass through nodes that are at least as far away.
Section 5
Why Dijkstra's algorithm works
The key argument
The algorithm finalises the closest unvisited node at each step. Suppose that node is X, with distance d. Any other route to X must leave the finalised nodes at some point, through some unvisited node Y. But Y's distance is at least d, and the rest of the route adds more. So no route to X can be shorter than d.
Derivation: why the closest unvisited node is final
Let X be the unvisited node with the smallest tentative distance d(X). Consider any other route from the start to X, and let Y be the first unvisited node on it.
Since X has the smallest tentative distance, d(Y) ≥ d(X). With non-negative weights, the length from Y to X is at least 0.
So no route to X is shorter than d(X), and its distance can safely be finalised. The argument needs every weight to be non-negative.
Negative weights
The proof breaks if an edge has a negative weight. Then a long route could become shorter by passing through a negative edge later. Dijkstra's algorithm would already have finalised the node, so it would never find the better route.
Common mistake: using Dijkstra's algorithm on a graph with negative weights. The algorithm finalises nodes on the assumption that later routes can only get longer. A negative edge breaks that, so a finalised distance can be wrong. Other algorithms, such as Bellman–Ford, handle negative weights.
Dijkstra's algorithm is greedy, but safely
Dijkstra's algorithm is a greedy algorithm: at each step it makes the choice that looks best right now, finalising the closest node. Greedy choices often go wrong, as the greedy walk shows. Here the choice is safe, because the proof above shows that the closest node can never be improved.
The difference is in what is chosen. The greedy walk picks the cheapest next edge, which ignores how far you have already come. Dijkstra's algorithm picks the smallest total distance from the start, which takes every route found so far into account.
Worked example 9: a negative edge
A directed graph has edges A→B of weight 2, A→C of weight 3 and C→B of weight −2. Run Dijkstra's algorithm from A and compare its answer for B with the true shortest distance.
| Working | Reason |
|---|---|
| Finalise A (0); set B to 2 and C to 3 | These come from A's direct edges |
| Finalise B (2), the smallest unvisited distance | B is now treated as final |
| Finalise C (3); the edge C→B gives 3 − 2 = 1, but B is already final | Finalised nodes are never updated |
| The algorithm reports B = 2, but the true shortest distance is 1 | The negative edge breaks the method |
Complexity
With a simple table, each of the n steps scans every node to find the smallest distance, so the algorithm is O(n²). Using a priority queue, a structure that always returns its smallest item quickly, it runs in about O((n + e) log n) for e edges. That is much faster on a large, sparse map.
Distances to every node
Dijkstra's algorithm finds the shortest distance from the start to every node, not just to one target. That makes it ideal when many routes from the same place are needed, such as a router working out the best way to every other network.
If only one target matters, the algorithm can stop as soon as that target is finalised. Its distance is then certain, and the rest of the graph need not be explored. This early stop is exactly what A* builds on.
Dijkstra's algorithm on large maps
A satnav's road graph may have millions of junctions. Dijkstra's algorithm, starting from your location, spreads out evenly in every direction, finalising junctions behind you as well as ahead. That wastes effort. A* fixes this by giving the search a sense of direction.
Check yourself. Why does Dijkstra's algorithm need every edge weight to be zero or more?
Show the answer
It finalises the closest unvisited node, assuming no later route can be shorter. A negative edge could make a later route shorter, so a node finalised too early could have the wrong distance.
Section 6
A* search
Adding a sense of direction
A* is a refinement of Dijkstra's algorithm for finding the shortest path to one particular goal. It uses two numbers for each node. The first, g(n), is the distance travelled from the start. The second, h(n), is a heuristic: an estimate of the distance still to go to the goal.
At each step A* expands the open node with the smallest f(n) = g(n) + h(n). This favours nodes that are close to the start and also look close to the goal. A* stops as soon as it expands the goal, so it often explores far fewer nodes than Dijkstra's algorithm.
Open and closed sets
A* keeps two sets of nodes. The open set holds nodes that have been reached but not yet expanded. The closed set holds nodes that have been expanded. At each step, A* moves the open node with the smallest f into the closed set and looks at its neighbours.
When a neighbour is first reached, or reached by a shorter route than before, its g value and previous node are updated and it joins the open set. This is the same updating rule as in Dijkstra's algorithm, with f used in place of the distance to choose the next node.
Heuristics
The heuristic is problem-specific. On a map, the straight-line distance to the goal is natural: no road can be shorter than a straight line. On a grid in a game, the number of squares across plus the number down, called the Manhattan distance, is common.
A heuristic is admissible if it never overestimates the true distance to the goal. With an admissible heuristic, A* is guaranteed to find the shortest path. Straight-line distance is admissible, because roads can only be longer than straight lines.
Common mistake: using a heuristic that overestimates the distance to the goal. An overestimate can make A* skip the true shortest route because it looks worse than it is. For A* to guarantee the shortest path, the heuristic must never be more than the real remaining distance.
Derivation: why an admissible heuristic finds the shortest path
Suppose the shortest route to the goal has length L. Every node n on that route has f(n) = g(n) + h(n). Since h never overestimates, h(n) is at most the true distance from n to the goal.
Now suppose A* were about to expand the goal G by a worse route, of length L′ > L. At the goal h(G) = 0, so its f value is that route's length.
Some node n on the shortest route is still open with f(n) ≤ L, so A* would expand it first. The goal can only be expanded by a route of length L.
Worked example 10: tracing A*
Find the shortest route from A to E with A*, using the heuristic h: A 6, B 6, C 3, D 2, E 0, F 1, G 8.
| Working | Reason |
|---|---|
| Expand A: B has f = 1 + 6 = 7 and C has f = 4 + 3 = 7 | f is distance so far plus the estimate |
| Tie on f = 7: expand C, which has the smaller h | The node that looks closer to the goal goes first |
| From C: D has f = 5 + 2 = 7 and F has f = 10 + 1 = 11; expand D | D now has the smallest f |
| From D: E has f = 7 + 0 = 7; expand E, the goal | A* stops when the goal is expanded |
| Route A, C, D, E, length 7, after expanding only 4 nodes | Dijkstra's algorithm finalised 6 nodes before E |
Why A* stops early
A* stops as soon as the goal is expanded, not when it is first reached. When the goal is first reached, a shorter route to it might still be waiting in the open set. Only when the goal has the smallest f of all open nodes is its route certain.
Worked example 11: A* without a heuristic
What does A* do if the heuristic is 0 for every node?
| Working | Reason |
|---|---|
| With h = 0, f(n) = g(n) for every node | The estimate adds nothing |
| A* then expands the node with the smallest distance so far | That is exactly Dijkstra's rule |
| On the road network it expands A, B, C, G, D and E | Six nodes, as Dijkstra's algorithm finalised |
| So Dijkstra's algorithm is A* with a heuristic of zero | A good heuristic is what makes A* faster |
Heuristics in practice
The better the heuristic, the fewer nodes A* expands. A heuristic of 0 is admissible but gives no guidance, so A* becomes Dijkstra's algorithm. A perfect heuristic, equal to the true distance, would lead A* straight to the goal. Real heuristics sit in between.
Satnavs use straight-line distance, which is easy to compute from map coordinates. Games on square grids use the Manhattan distance, or a diagonal version if characters can move diagonally. Choosing a heuristic that is both cheap to compute and close to the truth is the art of using A*.
Limits of A*
A* is only as good as its heuristic. If no sensible estimate of the remaining distance exists, A* has nothing to work with and falls back to Dijkstra's behaviour. And like Dijkstra's algorithm, it needs non-negative edge weights.
A* can also use a lot of memory, because its open set may hold many nodes on a large map. Game developers often break a map into regions, find a route between regions first, and then use A* within each region. That keeps the open set small.
Choosing an algorithm
Choose by the question being asked. To visit every node, use a traversal: BFS for layers or fewest edges, DFS for exploring and backtracking. For shortest distances from one node to all others, use Dijkstra's algorithm. For the shortest route to one goal, with a good heuristic available, use A*.
Check yourself. What makes a heuristic admissible, and why does it matter for A*?
Show the answer
A heuristic is admissible if it never overestimates the true distance to the goal. Then A* is guaranteed to find the shortest path, because it can never wrongly rule out a route that is really shorter.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Adjacency list | Each node's neighbours, with weights | D: B 7, C 1, E 2 | Space grows with the number of edges |
| Adjacency matrix | A grid of weights for every pair of nodes | Row A, column B holds 1 | Space n²; instant edge lookup |
| Breadth-first search | Visit layer by layer using a queue | A, B, C, D, G, F, E | Finds fewest edges, not least weight |
| Depth-first search | Go deep first, then backtrack, using recursion or a stack | A, B, D, C, F, E, G | Suits mazes, cycles and exploring |
| Dijkstra's algorithm | Finalise the closest unvisited node, update neighbours | A to E is 7 | Needs non-negative weights; O(n²) with a table |
| Previous-node links | The node each best distance came through | E came from D | Follow back from the goal for the path |
| A* search | Expand the smallest f = g + h | Expands A, C, D, E | Shortest path if h is admissible |
| Admissible heuristic | Never overestimates the distance to the goal | Straight-line distance | Overestimates can miss the best route |
Programming task
Programming task: route finder
Aim
Write a Python program that stores a weighted graph as an adjacency list, then finds shortest distances with Dijkstra's algorithm and recovers the route to a chosen node. Test it on the road network from this chapter.
Design
The graph is a dictionary mapping each node to a list of (neighbour, weight) pairs. Dijkstra's algorithm keeps a dictionary of distances, a dictionary of previous nodes, and a set of finalised nodes. A helper function follows the previous links back from the goal to build the route.
For clarity, the program picks the next node by scanning all unfinalised nodes, which is O(n²). The tests check distances, routes, an unreachable node and a start node equal to the goal.
Code
import math
def add_road(graph, a, b, w):
graph.setdefault(a, []).append((b, w))
graph.setdefault(b, []).append((a, w))
def dijkstra(graph, start):
dist = {node: math.inf for node in graph}
previous = {node: None for node in graph}
dist[start] = 0
done = set()
while len(done) < len(graph):
candidates = [n for n in graph if n not in done and dist[n] < math.inf]
if not candidates:
break
current = min(sorted(candidates), key=lambda n: dist[n])
done.add(current)
for neighbour, w in graph[current]:
if neighbour not in done and dist[current] + w < dist[neighbour]:
dist[neighbour] = dist[current] + w
previous[neighbour] = current
return dist, previous
def route(previous, goal):
path = [goal]
while previous[path[0]] is not None:
path.insert(0, previous[path[0]])
return path
roads = {}
for a, b, w in [("A","B",1), ("A","C",4), ("B","D",7), ("B","G",3), ("C","D",1),
("C","F",6), ("D","E",2), ("F","E",1), ("G","E",9)]:
add_road(roads, a, b, w)
dist, previous = dijkstra(roads, "A")
print(dist["E"], route(previous, "E"))
Sorting the candidates before taking the minimum breaks ties alphabetically, so the program finalises nodes in the same order as a hand trace. The route function builds the path backwards from the goal, inserting each previous node at the front.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | dist["E"] from A | 7 | The shortest distance found in worked example 7 |
| 2 | route(previous, "E") | ['A', 'C', 'D', 'E'] | The route, not just the distance |
| 3 | dist["F"] from A | 8 | A node improved late in the trace |
| 4 | route(previous, "F") | ['A', 'C', 'D', 'E', 'F'] | Matches worked example 8 |
| 5 | dist["G"] from A | 4 | A node reached through B |
| 6 | dist["A"] from A | 0 | The start node to itself |
| 7 | add an isolated node Z, then dist["Z"] | inf | An unreachable node keeps distance infinity |
Evaluation
The program reproduces the hand trace exactly, including the improvement of D from 8 to 5. Test 7 confirms that unreachable nodes are handled without crashing: the loop stops when no finite distances remain.
Scanning every node to find the minimum makes this version O(n²). Python's heapq module provides a priority queue, which would make it much faster on large maps. Adding a heuristic to the priority would turn it into A*.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. State the data structure used by breadth-first search and the one used by an iterative depth-first search.
Worked solution to Q1
Breadth-first search uses a queue, which is first in, first out, so it explores layer by layer. An iterative depth-first search uses a stack, which is last in, first out, so it goes deep before backtracking.
Q2. Give one advantage of an adjacency list over an adjacency matrix.
Worked solution to Q2
An adjacency list stores only the edges that exist, so it uses far less memory for a sparse graph. A matrix stores an entry for every pair of nodes, most of which may be empty.
Q3. In A*, what do g(n), h(n) and f(n) stand for?
Worked solution to Q3
The value g(n) is the distance travelled from the start to node n. The value h(n) is the heuristic estimate of the distance from n to the goal. Their sum, f(n), is the estimated total length of a route through n.
Rung 2: Application
Q4. A graph has edges P–Q, P–R, Q–S, R–S, S–T and Q–U. Give the breadth-first order from P, taking neighbours alphabetically.
Worked solution to Q4
Visit P and enqueue Q and R. Visit Q and enqueue S and U. Visit R; S is already queued. Visit S and enqueue T, then visit U and T. The order is P, Q, R, S, U, T.
Q5. Give the depth-first order of the same graph from P.
Worked solution to Q5
From P go to Q, then from Q to S, then from S to R, which has nothing new. Back at S, go to T. Back at Q, go to U. The order is P, Q, S, R, T, U.
Q6. A graph has edges S–A 3, S–B 1, B–A 1, A–C 2, B–C 5, C–T 1 and B–T 7. Use Dijkstra's algorithm to find the shortest distance from S to T.
Worked solution to Q6
Finalise S, giving A 3 and B 1. Finalise B, improving A to 2, and giving C 6 and T 8. Finalise A, improving C to 4. Finalise C, improving T to 5. The shortest distance is 5, along S, B, A, C, T.
Q7. In the road network, how many roads are on the route with the fewest roads from A to E, and is it the shortest route by distance?
Worked solution to Q7
Breadth-first search reaches E in the third layer, so the fewest roads is 3. Both A, B, G, E and A, C, D, E use three roads, but their lengths are 13 and 7. Fewest roads does not decide distance.
Rung 3: Analysis
Q8. Explain why always taking the cheapest road from the current town fails to find the shortest route from A to E in the road network.
Worked solution to Q8
From A the cheapest road leads to B, and from B the cheapest new road leads to G. From G the only way on is the road of 9 to E, giving 1 + 3 + 9 = 13. The cheap first steps lead to an expensive finish, while A, C, D, E costs only 7.
Q9. Trace Dijkstra's algorithm on the road network far enough to show how D's distance changes, and explain why it changes.
Worked solution to Q9
When B is finalised, D is set to 1 + 7 = 8. When C is finalised, the route through C gives 4 + 1 = 5, which is smaller, so D becomes 5. D was not yet finalised, so its distance could still improve.
Q10. Explain why A* expanded fewer nodes than Dijkstra's algorithm on the road network.
Worked solution to Q10
The heuristic made B and G look far from E, with f values that never became the smallest. So A* never expanded them. Dijkstra's algorithm has no sense of direction, so it finalised B and G simply because they were close to A.
Q11. A heuristic gives h(B) = 20 in the road network, but the shortest distance from B to E is 8. Explain the risk.
Worked solution to Q11
The heuristic says 20, but the real distance from B to E is 8, so it overestimates and is not admissible. A route through B would look much worse than it is. If that route were really the shortest, A* could miss it and return a longer one.
Rung 4: Stretch
Q12. Starting from E instead of A, list the depth-first order of the road network, and explain why it differs.
Worked solution to Q12
From E the search goes to D, then B, then A, then C, then F. It backtracks to B to reach G. The order is E, D, B, A, C, F, G. The start node decides which branches are explored first, so the order changes completely.
Q13. Explain why breadth-first search finds the fewest-edge path to every node in an unweighted graph.
Worked solution to Q13
BFS visits all nodes at distance 1 before any at distance 2, and so on, because the queue keeps them in order of discovery. So the first time it reaches a node, it has come by the fewest possible edges. Any shorter path would have reached it in an earlier layer.
Q14. Suggest a heuristic for A* on a grid where a character can move only up, down, left or right, and explain why it is admissible.
Worked solution to Q14
Use the Manhattan distance: the number of columns plus the number of rows between the square and the goal. Each move changes the row or the column by one, so no route can take fewer moves than this. It never overestimates, so it is admissible.
Exam practice
Exam technique and worked answer workshop
Trace questions on graphs are marked node by node. Always state the convention you are using, such as alphabetical order, and stick to it. Write the queue or stack after each step for BFS and DFS, because examiners award marks for the intermediate states, not just the final order.
For Dijkstra's algorithm, a table is the clearest layout. Use one column per node and one row per step, and cross out a distance when it improves. Mark finalised nodes clearly. Then follow the previous nodes back from the goal to give the path and its length.
In explanations, be precise about what each algorithm guarantees. BFS finds the fewest edges; Dijkstra's algorithm finds the smallest total weight if weights are non-negative; A* finds the shortest path to one goal if its heuristic is admissible.
Exam question 1 (4 marks · Paper 02 · about 5 minutes)
A graph has the edges P–Q, P–R, Q–S, R–S, S–T and Q–U. Neighbours are visited in alphabetical order.
(a) Give the order in which a breadth-first traversal from P visits the nodes. [2]
(b) Give the order in which a depth-first traversal from P visits the nodes. [2]
Mark scheme for exam question 1
- M1 breadth-first visits P's neighbours Q and R before any node two edges away
- A1 P, Q, R, S, U, T
- M1 depth-first follows Q to S before visiting R
- A1 P, Q, S, R, T, U
Exam question 2 (5 marks · Paper 02 · about 7 minutes)
A weighted graph has edges S–A 3, S–B 1, B–A 1, A–C 2, B–C 5, C–T 1 and B–T 7. Use Dijkstra's algorithm to find the shortest path from S to T and its length. Show the order in which nodes are finalised.
Mark scheme for exam question 2
- B1 S finalised first, with A at 3 and B at 1
- M1 B finalised next, improving A to 2
- M1 A then C finalised, with C at 4 and T improved to 5
- A1 finalised order S, B, A, C, T
- A1 path S, B, A, C, T with length 5
Exam question 3 (5 marks · Paper 02 · about 7 minutes)
(a) Describe how breadth-first search uses a queue to traverse a graph. [3]
(b) Explain why breadth-first search does not always find the shortest route in a weighted graph. [2]
Mark scheme for exam question 3
- B1 the start node is added to the queue and marked as discovered
- B1 the node at the front is removed and visited
- B1 its undiscovered neighbours are marked and added to the back of the queue, repeating until the queue is empty
- B1 breadth-first search finds the route with the fewest edges
- B1 a route with more edges can have a smaller total weight, so the fewest edges is not always the shortest distance
Exam question 4 (5 marks · Paper 02 · about 7 minutes)
Use A* to find the shortest route from A to E in this chapter's road network. Use the heuristic A 6, B 6, C 3, D 2, E 0, F 1, G 8. Ties in f are broken by the smaller h. Give the order nodes are expanded and the route found.
Mark scheme for exam question 4
- M1 f = g + h calculated: B and C both have f = 7 from A
- A1 C expanded before B because its h is smaller
- M1 from C, D has f = 7 and F has f = 11, so D is expanded
- A1 expanded order A, C, D, E
- A1 route A, C, D, E with length 7
Exam question 5 (6 marks · Paper 02 · about 9 minutes)
A games company needs characters to find routes around a map of 10,000 grid squares with obstacles. Discuss whether it should use breadth-first search, Dijkstra's algorithm or A*.
Mark scheme for exam question 5
Level 3 (5–6 marks): a clear comparison of all three algorithms, explaining what each guarantees and how much of the map it explores. The answer discusses heuristics and admissibility for A*. It reaches a justified recommendation for this context, with accurate technical terms.
Level 2 (3–4 marks): a correct comparison of at least two algorithms with some reference to the game. The discussion of heuristics or the recommendation is limited.
Level 1 (1–2 marks): some relevant points, such as that A* is faster or that BFS ignores weights, with little explanation. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- breadth-first search finds the fewest moves if every move costs the same
- it ignores different costs, such as slow terrain like mud or water
- Dijkstra's algorithm finds the cheapest route when moves have different costs
- Dijkstra's algorithm spreads out in every direction, exploring much of the map
- A* adds a heuristic estimate of the distance to the goal, so it heads towards it
- on a grid, the Manhattan distance is a natural heuristic
- if the heuristic is admissible, A* still finds the shortest route
- A* explores far fewer squares, which matters when many characters move every frame
- recommendation: A* with an admissible heuristic such as Manhattan distance
Annotated model answer: exam question 5
"Breadth-first search explores the map in layers from the character, so it finds the route with the fewest moves. That is enough if every square costs the same to cross. But if some squares, such as mud, are slower, the fewest moves is not the quickest route." (BFS and its limit.)
"Dijkstra's algorithm handles different move costs, because it always extends the closest square so far. It is guaranteed to find the cheapest route. But it has no sense of direction, so it spreads out in every direction and may explore much of the 10,000 squares." (Dijkstra's strength and cost.)
"A* adds a heuristic, such as the Manhattan distance to the goal. It expands squares with the smallest f = g + h, so it heads towards the goal and explores far fewer squares. If the heuristic never overestimates, A* still finds the shortest route." (A and admissibility.)*
"Games move many characters every frame, so speed matters. The company should use A* with the Manhattan distance, which is admissible on a grid where moves are up, down, left and right." (A justified recommendation.)
This answer reaches Level 3 and scores 6 marks. It compares all three, links each to the game and chooses clearly.
Exam question 6 (5 marks · Paper 02 · about 7 minutes)
A directed graph has edges A→B of weight 2, A→C of weight 3 and C→B of weight −2.
(a) State the distance Dijkstra's algorithm gives from A to B. [1]
(b) State the true shortest distance from A to B. [1]
(c) Explain why the algorithm gives the wrong answer. [3]
Mark scheme for exam question 6
- B1 2
- B1 1, along A, C, B
- B1 B is finalised as soon as it is the closest unvisited node
- B1 the algorithm assumes later routes can only be longer, which needs non-negative weights
- B1 the negative edge C→B makes a later route shorter, but B is never updated after being finalised
Exam question 7 (5 marks · Paper 02 · about 7 minutes)
Write a recursive procedure dfs(graph, node, visited) that prints each node of a graph in depth-first order. The graph is an adjacency list, and visited is a set that starts empty.
Mark scheme for exam question 7
- B1 the current node added to visited
- B1 the current node printed
- M1 a loop over the neighbours of the current node
- M1 a check that a neighbour is not in visited before visiting it
- A1 a recursive call dfs(graph, neighbour, visited) for each unvisited neighbour
Annotated model answer: exam question 7
procedure dfs(graph, node, visited)
visited.add(node)
print(node)
for each neighbour in graph[node]
if neighbour not in visited then
dfs(graph, neighbour, visited)
endif
next neighbour
endprocedure
Adding the node to visited and printing it earn the first two marks. The loop over neighbours and the check against visited earn the method marks. The recursive call is what makes the search go deep before trying the next neighbour, and earns the final mark.
Exam question 8 (5 marks · Paper 01 · about 7 minutes)
A road map has 50,000 junctions, each joined to about 3 roads.
(a) Calculate the number of entries in an adjacency matrix for this map. [1]
(b) Estimate the number of neighbour entries in an adjacency list for this map. [2]
(c) Recommend a representation, and give one advantage of the other. [2]
Mark scheme for exam question 8
- B1 50,000 × 50,000 = 2,500,000,000 entries
- M1 about 50,000 × 3 ÷ 2 = 75,000 roads
- A1 about 150,000 neighbour entries, as each road appears in two lists
- B1 an adjacency list, because the graph is sparse and the list uses far less memory
- B1 a matrix can check whether two junctions are joined with a single lookup
Connections
Synoptic link
These algorithms depend on data structures from earlier chapters. The queue that drives breadth-first search and the stack behind depth-first search come from Arrays, records, stacks and queues. Graphs and adjacency lists are introduced in Linked lists, hash tables, graphs and trees.
Their efficiency is analysed with the tools of Algorithm analysis and Big O notation. In Networks, protocols and the internet, routers use shortest-path algorithms to choose where to send each packet.
Synoptic question 1. On the road network, a greedy walk from A to E takes the cheapest road each time. By what percentage of the greedy route's length is Dijkstra's route shorter?
Answer to synoptic question 1
The greedy walk goes A, B, G, E, with length 1 + 3 + 9 = 13. The best route is 7. The saving is 13 − 7 = 6, which is 6 ÷ 13 × 100 ≈ 46% of the greedy route.
Recap
Recap and next step
- A graph is nodes joined by edges, which may be directed or weighted; adjacency lists suit sparse graphs and matrices suit dense ones.
- Breadth-first search uses a queue, visits nodes layer by layer and finds the fewest edges to each node.
- Depth-first search uses recursion or a stack, follows one path as deep as it can, then backtracks.
- Dijkstra's algorithm repeatedly finalises the closest unvisited node and updates its neighbours; previous-node links give the path.
- Dijkstra's algorithm needs non-negative weights and is O(n²) with a simple table.
- A* expands the node with the smallest f = g + h; with an admissible heuristic it finds the shortest path while exploring fewer nodes.
Next chapter: Problem solving for the algorithms paper brings these algorithms together with the rest of the course in extended exam-style problems.
For your exam board
OCR A Level Computer Science (H446): this chapter covers the graph algorithms in section 2.3.1, Algorithms, in Component 02, Algorithms and programming: depth-first and breadth-first traversal, and Dijkstra's shortest path algorithm and the A* algorithm, with their uses and comparison.
AQA A Level Computer Science (7517): graph traversal, breadth-first and depth-first, and Dijkstra's shortest path algorithm appear in the fundamentals of algorithms section, assessed on Paper 1. A* is not required by AQA.