Graph traversal algorithms systematically visit every vertex in a graph exactly once. The two main algorithms are Breadth-First Search (BFS) and Depth-First Search (DFS).
BFS explores a graph level by level — visiting all neighbours of the current vertex before moving deeper. BFS uses a queue.
// BFS from start node S
1. Create a QUEUE and add S to it
2. Mark S as visited
3. WHILE queue is not empty:
a. Dequeue the front vertex V
b. Process V (output it)
c. FOR each unvisited neighbour N of V:
Mark N as visited
Enqueue N
4. END WHILE
// Graph edges: A-B, A-C, B-D, B-E, C-F // BFS from A: Queue: [A] → dequeue A → visit A, enqueue B,C Queue: [B,C] → dequeue B → visit B, enqueue D,E Queue: [C,D,E] → dequeue C → visit C, enqueue F Queue: [D,E,F] → dequeue D → visit D Queue: [E,F] → dequeue E → visit E Queue: [F] → dequeue F → visit F Order: A, B, C, D, E, F
DFS explores a graph by going as deep as possible along one path before backtracking. DFS uses a stack (or recursion).
// DFS from start node S
1. Create a STACK and push S onto it
2. WHILE stack is not empty:
a. Pop top vertex V from stack
b. IF V not visited:
Mark V as visited
Process V (output it)
FOR each unvisited neighbour N of V:
Push N onto stack
3. END WHILE
// Same graph: A-B, A-C, B-D, B-E, C-F // DFS from A (using stack): Stack: [A] → pop A → visit A, push C,B (reverse neighbour order) Stack: [C,B] → pop B → visit B, push E,D Stack: [C,E,D] → pop D → visit D Stack: [C,E] → pop E → visit E Stack: [C] → pop C → visit C, push F Stack: [F] → pop F → visit F Order: A, B, D, E, C, F
| Feature | BFS | DFS |
|---|---|---|
| Data structure | Queue (FIFO) | Stack (LIFO) or recursion |
| Exploration order | Level by level (breadth) | Deep first, then backtrack |
| Shortest path (unweighted) | Yes | No |
| Memory | Higher (stores all level nodes) | Lower (one path at a time) |
| Finds all nodes? | Yes | Yes |
8 questions · instantly marked · AQA 7517 standard
| Term | Definition |
|---|
10 questions · 10 minutes