Loading lessons...
Graph Traversals - Breadth-First & Depth-First Search
Graph Traversals - Breadth-First & Depth-First Search
Traversing a graph means visiting every vertex reachable from a start vertex exactly once. Unlike a tree, a graph may contain cycles and a vertex may be reachable along many paths, so a traversal must remember which vertices it has already seen - otherwise it would loop forever. The two standard methods are breadth-first search (BFS) and depth-first search (DFS).
1. Vertex States
The textbook (Lipschutz) algorithms give each vertex a STATUS:
| STATUS | State | Meaning |
|---|---|---|
| 1 | Ready | Not yet reached |
| 2 | Waiting | Reached and placed in the queue/stack, not yet processed |
| 3 | Processed | Removed and processed |
A vertex is added to the queue or stack only while it is ready, so no vertex is processed twice.
2. Breadth-First Search (BFS)
Idea: visit the start vertex, then all its neighbours, then all their unvisited neighbours, and so on - level by level, like ripples spreading in water. A queue (FIFO) remembers the order in which vertices were reached.
Algorithm BFS(G, S)
for each vertex V of G do
STATUS[V] ← 1 // ready
ENQUEUE(Q, S); STATUS[S] ← 2 // waiting
while Q is not empty do
N ← DEQUEUE(Q)
process N; STATUS[N] ← 3 // processed
for each neighbour M of N do
if STATUS[M] = 1 then
ENQUEUE(Q, M)
STATUS[M] ← 23. Depth-First Search (DFS)
Idea: go as deep as possible along one path; when a vertex has no unvisited neighbour, backtrack to the previous vertex and try another branch - like exploring a maze by always taking the next unexplored corridor. A stack (or recursion, which uses the call stack) remembers where to backtrack to.
Recursive DFS
Algorithm DFS(G, V)
VISITED[V] ← TRUE
process V
for each neighbour W of V do
if VISITED[W] = FALSE then
DFS(G, W) // go deeper firstStack version (Lipschutz)
Identical to BFS but with a STACK: push the start vertex; repeatedly pop the top vertex, process it, and push all its ready neighbours (setting them to waiting).
4. Worked Example: the A-F Graph
Edges: A-B, A-C, B-C, B-D, C-D, C-E, D-E, D-F (and a self-loop at F). Neighbours are taken in alphabetical order.
B --------- D --------- F (self-loop at F)
/ | / |
A | / |
\ | / |
C --------- EAdjacency lists: A: B C | B: A C D | C: A B D E | D: B C E F | E: C D | F: D F
Trace from A (queue: front on the left; stack: top on the right):
| BFS step | Process | QUEUE after | DFS step | Process | STACK after |
|---|---|---|---|---|---|
| start | - | A | start | - | A |
| 1 | A | B C | 1 | A | B C |
| 2 | B | C D | 2 | C | B D E |
| 3 | C | D E | 3 | E | B D |
| 4 | D | E F | 4 | D | B F |
| 5 | E | F | 5 | F | B |
| 6 | F | - | 6 | B | - |
- BFS order: A B C D E F
- DFS order (stack version): A C E D F B
- DFS order (recursive): A B C D E F - from A go to B, from B to C, from C to D, from D to E; E has no new neighbour, so backtrack to D and go to F.
Different (equally correct) orders arise from different neighbour orders - in an exam, state the order you use.
BFS tree and DFS tree
The edges used to reach new vertices form a spanning tree of the (connected) graph.
BFS tree (levels) Recursive DFS tree
level 0: A A
/ \ |
level 1: B C B
| | |
level 2: D E C
| |
level 3: F D
/ \
E FThe BFS level of each vertex is its shortest distance (in edges) from A: B and C are 1 edge away, D and E 2, F 3. The DFS tree is long and thin because DFS dives deep.
5. Analysis
Each vertex is enqueued/pushed and processed once, and each adjacency list is scanned once.
| Representation | BFS / DFS time | Why |
|---|---|---|
| Adjacency list | O(n + e) | Every vertex once + every list node once |
| Adjacency matrix | O(n2) | Scanning row of each vertex costs n |
Extra space: O(n) for the visited array plus the queue or stack (or recursion depth).
6. BFS vs DFS
| Basis | BFS | DFS |
|---|---|---|
| Data structure | Queue (FIFO) | Stack (LIFO) or recursion |
| Order of visiting | Level by level, nearest first | Deep along one path, then backtrack |
| Spanning tree | Short and wide | Long and thin |
| Shortest path (unweighted) | Yes - the first time a vertex is reached is by a shortest path | No |
| Memory | Can hold a whole level (wide graphs) | Holds one path (deep graphs) |
| Typical uses | Shortest paths, level order, bipartite test, web crawling, nearest neighbours in networks | Cycle detection, topological sort, connected/strongly connected components, maze solving, backtracking |
| Time | O(n + e) | O(n + e) |
7. Applications of Traversal
Connected components
Run BFS or DFS from any unvisited vertex; every vertex it reaches is in the same component. Repeat from the next unvisited vertex.
Algorithm COMPONENTS(G)
COUNT ← 0
for each vertex V do VISITED[V] ← FALSE
for each vertex V of G do
if VISITED[V] = FALSE then
COUNT ← COUNT + 1
DFS(G, V) // marks one whole component
return COUNTThe graph is connected exactly when COUNT = 1.
Cycle detection
- Undirected graph: during DFS, reaching an already-visited vertex that is not the parent of the current vertex means a cycle.
- Directed graph: reaching a vertex that is still on the recursion stack (a back edge) means a cycle.
Other uses
- Path finding: is there a path from u to v? (Traverse from u and see whether v is reached.)
- Topological sort of a DAG: output vertices in reverse order of DFS finishing times (see the Beyond Syllabus lesson on topological sorting).
- Spanning tree of an unweighted graph: the BFS or DFS tree.
Key points to remember - Mark vertices as visited - graphs can have cycles. - BFS: queue, level by level, gives shortest paths in unweighted graphs. - DFS: stack/recursion, go deep then backtrack; used for cycles, components and topological sort. - Both: O(n + e) with adjacency lists, O(n2) with a matrix. - A-F graph from A: BFS A B C D E F; stack DFS A C E D F B.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. Write the BFS and DFS algorithms using STATUS (ready, waiting, processed). Trace both from A on the given graph. (10 Marks)
- Write: both algorithms, the queue and stack trace table, and the resulting orders.
- Q2. Differentiate between BFS and DFS. Give two applications of each. (5 Marks)
- Write: the comparison table; BFS → shortest path, level order; DFS → cycle detection, topological sort.
- Q3. How can a traversal find the connected components of a graph? (5 Marks)