4. Find the error in this DFS code snippet and select the fix:
graph = {0: [1], 1: [2], 2: []}
visited = set()
def dfs(node):
if node in visited:
return
print(node)
for neighbor in graph[node]:
dfs(neighbor)
dfs(0)
medium
A. Add 'visited.add(node)' after printing node to mark it visited.
B. Change 'if node in visited' to 'if node not in visited'.
C. Remove the 'return' statement inside the if condition.
D. Add 'visited.remove(node)' after recursive calls.
Solution
Step 1: Identify missing visited marking
The code never adds nodes to visited, so it revisits nodes infinitely.
Step 2: Fix by adding visited marking
Adding 'visited.add(node)' after printing marks node as visited to avoid revisits.
Final Answer:
Add 'visited.add(node)' after printing node to mark it visited. -> Option A
Quick Check:
Mark visited after visiting node [OK]
Hint: Always add node to visited set after visiting [OK]
Common Mistakes:
Forgetting to mark nodes visited
Incorrect if condition logic
Removing nodes from visited incorrectly
5. Given a directed graph represented as adjacency list:
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1]}
Write the DFS traversal order starting from node 0 that detects cycles by tracking recursion stack. What is the order of nodes visited before detecting a cycle?
hard
A. 0 1 2
B. 0 2 3 1
C. 0 1 2 3
D. 0 2 1 3
Solution
Step 1: Start DFS from node 0 and track recursion stack
Visit 0, then 1, then 2, then 3. At 3, neighbor 1 is in recursion stack, cycle detected.
Step 2: List nodes visited before cycle detection
Nodes visited in order: 0, 1, 2, 3 before cycle found.
Final Answer:
0 1 2 3 -> Option C
Quick Check:
DFS with cycle detection visits 0 1 2 3 [OK]
Hint: Track recursion stack to detect cycles during DFS [OK]
Common Mistakes:
Ignoring recursion stack for cycle detection
Stopping traversal too early
Visiting nodes in wrong order
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.