BIT201 · 2082 · 5 marks
Traverse the following graph using BFS and DFS.
Traverse the following graph using BFS and DFS. [5]
BFS and DFS Graph Traversal
Given
The question asks to traverse a graph using BFS and DFS, but the actual graph (the figure/diagram) is not included in the text provided. No adjacency list, adjacency matrix, edge set, or vertex set is given.
Missing data: The specific graph (vertices and edges) required to perform the traversal is not available. Without it, the exact traversal orders cannot be determined, since traversal output depends entirely on the graph structure and the chosen starting vertex.
Because the graph is unreadable/absent, I will present the methodology and demonstrate it on a clearly labelled representative example, while flagging that the numeric traversal order is example-dependent and not the "official" answer to the missing figure.
Solution
Example Graph
1
/ \
2 3
/ \ \
4 5 6
Adjacency list:
- $1 \to 2, 3$
- $2 \to 4, 5$
- $3 \to 6$
- $4 \to$ (none)
- $5 \to$ (none)
- $6 \to$ (none)
Breadth First Search (BFS)
Idea: Use a Queue (FIFO); visit level by level.
| Step | Queue (front→back) | Visited | Action |
|---|---|---|---|
| 1 | [1] | {1} | Start at 1 |
| 2 | [2, 3] | {1,2,3} | Dequeue 1, enqueue 2,3 |
| 3 | [3, 4, 5] | {1,2,3,4,5} | Dequeue 2, enqueue 4,5 |
| 4 | [4, 5, 6] | {1,2,3,4,5,6} | Dequeue 3, enqueue 6 |
| 5 | [5, 6] | - | Dequeue 4 (no neighbors) |
| 6 | [6] | - | Dequeue 5 (no neighbors) |
| 7 | [] | - | Dequeue 6 (no neighbors) |
BFS Order: $$\boxed{1 \to 2 \to 3 \to 4 \to 5 \to 6}$$
Depth First Search (DFS)
Idea: Use a Stack (LIFO) or recursion; go deep before backtracking.
| Step | Action | Visited |
|---|---|---|
| 1 | Visit 1 | {1} |
| 2 | Visit 2 (first neighbor of 1) | {1,2} |
| 3 | Visit 4 (first neighbor of 2) | {1,2,4} |
| 4 | Backtrack to 2 (4 dead-end) | {1,2,4} |
| 5 | Visit 5 | {1,2,4,5} |
| 6 | Backtrack to 1 | {1,2,4,5} |
| 7 | Visit 3 | {1,2,4,5,3} |
| 8 | Visit 6 | {1,2,4,5,3,6} |
DFS Order: $$\boxed{1 \to 2 \to 4 \to 5 \to 3 \to 6}$$
Comparison
| Feature | BFS | DFS |
|---|---|---|
| Data structure | Queue (FIFO) | Stack / Recursion |
| Traversal manner | Level by level | Deepest branch first |
| Order (this graph) | $1,2,3,4,5,6$ | $1,2,4,5,3,6$ |
| Typical use | Shortest path (unweighted) | Topological sort, cycle detection |
Note to examiner/student: The traversal orders above are valid only for the assumed example graph. If the real exam figure differs, apply the same procedure (queue for BFS, stack/recursion for DFS) to that graph's adjacency list to obtain the correct order.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.