Question DSA-GRAPH-0007
EasyWhat is the output of this code?
g = {0: [1, 2], 1: [3], 2: [3], 3: [4], 4: []}
seen, order = set(), []
def dfs(u):
seen.add(u)
order.append(u)
for v in g[u]:
if v not in seen:
dfs(v)
dfs(0)
print(order)
- A.
[0, 1, 3, 4, 2]
- B.
[0, 2, 3, 4, 1]
- C.
Show answer and explanation
Answer: A
DFS goes as deep as possible first: 0 → 1 → 3 → 4, then backtracks to visit 2.