A graph is a data structure consisting of vertices (nodes) connected by edges (arcs). Graphs can be undirected, directed, or weighted. A graph traversal visits every reachable vertex exactly once, following edges from a chosen starting vertex.
Two traversal algorithms are required for AQA A-Level: breadth-first search (BFS) and depth-first search (DFS). They differ in the order they explore the graph — and that difference determines which problems each one solves.
Both algorithms maintain a visited set to ensure no vertex is processed twice. Without this, the traversal would loop indefinitely in any graph containing cycles.
| Algorithm | Data structure | Exploration order |
|---|
| BFS | Queue (FIFO) | Level by level from source — all vertices at distance 1, then distance 2, then distance 3, … |
| DFS | Stack (LIFO) or recursion | As deep as possible along one branch before backtracking |
The graph used throughout this lesson:
A
/ \
B C
/ \ \
D E F
Edges: A–B, A–C, B–D, B–E, C–F. Starting vertex: A.