Data Structures & AlgorithmsModerateWipro · Accenture pattern

BFS from vertex 0 visits neighbours in increasing order. What is the BFS order and the DFS (recursive) order?

BFS from vertex 0 visits neighbours in increasing order. What is the BFS order and the DFS (recursive) order?
g = {0: [1, 2], 1: [3, 4], 2: [4, 5], 3: [6], 4: [6], 5: [6], 6: []}
from collections import deque
seen, q, bfs = {0}, deque([0]), []
while q:
    u = q.popleft(); bfs.append(u)
    for v in g[u]:
        if v not in seen: seen.add(v); q.append(v)
dfs, vis = [], set()
def go(u):
    vis.add(u); dfs.append(u)
    for v in g[u]:
        if v not in vis: go(v)
go(0)
print(bfs, dfs)
  1. A. [0, 1, 2, 3, 4, 5, 6] [0, 1, 3, 4, 6, 2, 5]
  2. B. [0, 1, 2, 3, 4, 5, 6] [0, 1, 3, 6, 4, 2, 5]
  3. C. [0, 1, 3, 6, 4, 2, 5] [0, 1, 2, 3, 4, 5, 6]
  4. D. [0, 1, 2, 4, 3, 5, 6] [0, 1, 3, 6, 4, 2, 5]

Correct answer: B. [0, 1, 2, 3, 4, 5, 6] [0, 1, 3, 6, 4, 2, 5]

BFS goes level by level: 0 | 1, 2 | 3, 4, 5 | 6. DFS goes deep first: 0 → 1 → 3 → 6, backtracks to 1 → 4 (6 already seen), then 2 → 5. Both are O(V + E).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic