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)- A. [0, 1, 2, 3, 4, 5, 6] [0, 1, 3, 4, 6, 2, 5]
- B. [0, 1, 2, 3, 4, 5, 6] [0, 1, 3, 6, 4, 2, 5]
- C. [0, 1, 3, 6, 4, 2, 5] [0, 1, 2, 3, 4, 5, 6]
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Run Dijkstra from A on the weighted directed graph. In what order are vertices finalised (popped), and what is dist[E]? python import…
- Prim's algorithm from vertex 0 on the undirected graph below. In what order are vertices added and what is the MST weight? python import…
- Kahn's topological sort with a FIFO queue (initial zero-indegree vertices in increasing order). What is printed? python from collections…
- Kruskal's algorithm: which edges are accepted, in order, for the graph below? python edges = sorted([(7, 'A', 'B'), (5, 'A', 'D'), (8…
- How many times is the base case reached when computing C(5, 2) with the plain recursion C(n, k) = C(n−1, k−1) + C(n−1, k)? python base = 0…
- What is printed? (Tower of Hanoi: number of moves and the 5th move) python moves = [] def hanoi(n, a, b, c): if n == 0: return hanoi(n…