- Asked 4/14
- 2069 Bhadra · 5 marks
- 2073 Bhadra · 3 marks
BFS and DFS with example
Short answer
DFS uses a stack to go deep; BFS uses a queue to visit level by level. In the example graph with A connected to B and C, B to D and E, C to F, and E-F, DFS from A gives A B D E F C, while BFS gives A B C D E F. Both have O(V+E) time.
Explain depth first traversal and breadth first traversal in graph with suitable example.
Depth first traversal (DFS)
Goes as deep as possible along each path, then backtracks. Uses a stack (or recursion). From a vertex, move to an unvisited neighbour; when none remains, pop back.
int adj[N][N], visited[N], n;
void dfs(int v) {
visited[v] = 1;
printf("%d ", v);
for (int w = 0; w < n; w++)
if (adj[v][w] && !visited[w])
dfs(w);
}
Breadth first traversal (BFS)
Visits the start vertex, then all its neighbours, then their neighbours, level by level. Uses a queue.
int adj[N][N], visited[N], n;
void bfs(int s) {
int queue[N], front = 0, rear = 0;
visited[s] = 1; queue[rear++] = s;
while (front < rear) {
int v = queue[front++]; /* dequeue */
printf("%d ", v);
for (int w = 0; w < n; w++)
if (adj[v][w] && !visited[w]) {
visited[w] = 1;
queue[rear++] = w; /* enqueue */
}
}
}
Example graph
A
/ \
B C
/ \ \
D E---F
Edges: A-B, A-C, B-D, B-E, C-F, E-F. Adjacency lists (alphabetical): A: B, C; B: A, D, E; C: A, F; D: B; E: B, F; F: C, E.
BFS from A (queue):
| Step | Dequeued | Newly enqueued | Queue after step | Output |
|---|---|---|---|---|
| 0 | - | A | A | |
| 1 | A | B, C | B C | A |
| 2 | B | D, E | C D E | A B |
| 3 | C | F | D E F | A B C |
| 4 | D | none | E F | A B C D |
| 5 | E | none (F already queued) | F | A B C D E |
| 6 | F | none | empty | A B C D E F |
BFS order: A B C D E F
DFS from A (stack, alphabetical order): A → B → D (dead end, back to B) → E → F → C.
DFS order: A B D E F C
Both take O(V + E) time with adjacency lists.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Depth first traversal in graph · Data Structure and Algorithm, chapter 10 · asked 4×
- Breadth first traversal in graph · Data Structure and Algorithm, chapter 10 · asked 2×
- Differences between DFS and BFS · Data Structure and Algorithm, chapter 10
- Searching: BFS vs DFS comparison · Artificial Intelligence, chapter 3 · asked 5×
- Informed vs blind search; DFS vs BFS · Artificial Intelligence, chapter 3
- Rectangular beam dimensions, depth twice breadth · Strength of Materials, chapter 7