AQA 7517, section 4.3.1.1
Traversing a graph means visiting every vertex that can be reached from a starting vertex, in a systematic order. There are two standard methods, breadth-first search (BFS) and depth-first search (DFS). They differ in the order that they explore the graph.
The examples on this page use this graph. Neighbours are always taken in alphabetical order.
As an adjacency list:
graph = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
Breadth-first search
Breadth-first search explores level by level. It visits the start vertex, then all of its neighbours, then all of their unvisited neighbours, and so on, spreading out like ripples in a pond. It uses a queue.
Algorithm
- Put the start vertex in the queue and mark it as visited.
- While the queue isn't empty: remove the vertex at the front and visit it. Add each of its unvisited neighbours to the rear of the queue, marking them as visited.
def bfs(graph, start):
visited = [start]
queue = [start]
order = []
while queue:
v = queue.pop(0) # remove from the front
order.append(v)
for n in graph[v]:
if n not in visited:
visited.append(n)
queue.append(n) # add to the rear
return order
print(bfs(graph, "A")) # ['A', 'B', 'C', 'D', 'E', 'F']
Trace
| Remove from queue | Visit order so far | Queue after |
|---|---|---|
| (start) | A | |
| A | A | B, C |
| B | A, B | C, D, E |
| C | A, B, C | D, E, F |
| D | A, B, C, D | E, F |
| E | A, B, C, D, E | F |
| F | A, B, C, D, E, F | (empty) |
Typical application
Because BFS reaches every vertex using the fewest edges possible, it finds the shortest path in an unweighted graph. For example, the fewest number of connections between two people on a social network, or the fewest moves in a puzzle.
Depth-first search
Depth-first search goes as deep as possible down one path before backing up. It follows an edge to a new vertex, and keeps going until it reaches a vertex with no unvisited neighbours, then goes back (backtracks) to the last vertex that still has an unexplored neighbour. It uses a stack, either an explicit one, or the call stack when written recursively.
Algorithm (using a stack)
- Push the start vertex onto the stack.
- While the stack isn't empty: pop a vertex. If it hasn't been visited, visit it and push its neighbours onto the stack.
To visit neighbours in alphabetical order, push them in reverse order, so the first neighbour is on top.
def dfs(graph, start):
visited = []
stack = [start]
while stack:
v = stack.pop()
if v not in visited:
visited.append(v)
for n in reversed(graph[v]):
stack.append(n)
return visited
print(dfs(graph, "A")) # ['A', 'B', 'D', 'E', 'F', 'C']
The same idea written recursively is shorter:
def dfs_rec(graph, v, visited):
visited.append(v)
for n in graph[v]:
if n not in visited:
dfs_rec(graph, n, visited)
return visited
Trace
| Step | Pop | Visited | Stack after (top on the right) |
|---|---|---|---|
| 1 | A | A | C, B |
| 2 | B | A, B | C, E, D, A |
| 3 | A | (already visited) | C, E, D |
| 4 | D | A, B, D | C, E, B |
| 5 | B | (already visited) | C, E |
| 6 | E | A, B, D, E | C, F, B |
| 7 | B | (already visited) | C, F |
| 8 | F | A, B, D, E, F | C, E, C |
| 9 | C | A, B, D, E, F, C | (rest already visited) |
The visit order is A, B, D, E, F, C. It went down to D first, then backed up to B to reach E, then followed E to F and finally C.
Typical application
DFS is good for exploring every possibility down one route before trying another, such as navigating a maze: go along a corridor until you hit a dead end, then backtrack to the last junction.
BFS and DFS compared
| Breadth-first | Depth-first | |
|---|---|---|
| Data structure | Queue | Stack (or recursion) |
| Explores | Level by level, nearest first | One path as far as it goes, then backtracks |
| Finds | Shortest path (fewest edges) in an unweighted graph | A path, not necessarily the shortest |
| Typical use | Shortest route, nearest neighbours | Mazes, checking connectivity, backtracking |
Exam tip: in a trace, show the visit order and the state of the queue or stack at each step. State the data structure (queue for BFS, stack for DFS), because that is a common mark. Take neighbours in the order the question says, and use alphabetical or numerical order if it doesn't say.
Check yourself
Which data structure does breadth-first search use? And depth-first?
Breadth-first uses a queue. Depth-first uses a stack (or recursion, which uses the call stack).
Which traversal finds the shortest path in an unweighted graph?
Breadth-first search.
Give a typical application of depth-first search
Navigating a maze, because it follows one path as far as possible and backtracks when it reaches a dead end.
Using the graph above, what is the breadth-first order starting at C?
C, A, F, B, E, D. C's neighbours are A and F. Then A adds B, and F adds E. Then B adds D.