Visit 0, then explore neighbors in ascending order: 1, then 2.
Step 2: Explore neighbor 1
From 1, visit 3 (only neighbor), then backtrack.
Step 3: Explore neighbor 2
Node 2 has no neighbors, so visit and backtrack.
Final Answer:
[0, 1, 3, 2] -> Option C
Quick Check:
DFS order = 0,1,3,2 [OK]
Hint: Visit neighbors in order, go deep first [OK]
Common Mistakes:
Visiting node 2 before node 1
Not backtracking properly
Confusing BFS order with DFS
4. Given the following DFS code snippet, what is the error?
void dfs(int node, vector<bool> &visited, vector &graph) {
visited[node] = true;
for (int i = 0; i < graph[node].size(); i++) {
int neighbor = graph[node][i];
if (visited[neighbor] = false) {
dfs(neighbor, visited, graph);
}
}
}
medium
A. The function should return an int instead of void
B. The loop should use 'i <= graph[node].size()' instead of '<'
C. The visited vector should be passed by value, not reference
D. The condition 'if (visited[neighbor] = false)' uses assignment instead of comparison
Solution
Step 1: Check the if condition inside the loop
The condition uses '=' which assigns false instead of comparing.
Step 2: Understand the impact of assignment in condition
This causes the condition to always be false, so DFS won't recurse properly.
Final Answer:
The condition 'if (visited[neighbor] = false)' uses assignment instead of comparison -> Option D
Quick Check:
Use '==' for comparison, not '=' [OK]
Hint: Use '==' to compare, not '=' [OK]
Common Mistakes:
Using '=' instead of '==' in conditions
Loop boundary off-by-one errors
Passing visited by value causing no effect
5. You have a graph with 5 nodes (0 to 4) and edges: 0-1, 0-2, 1-3, 1-4. Using DFS starting at node 0, how can you modify the algorithm to count the number of nodes reachable from node 0?
hard
A. Add a counter variable incremented each time a node is visited during DFS
B. Count nodes after DFS by checking which nodes have no neighbors
C. Use BFS instead of DFS to count nodes reachable
D. Count nodes by summing the degrees of all nodes
Solution
Step 1: Understand counting reachable nodes
Counting nodes visited during DFS means incrementing a counter when marking a node visited.
Step 2: Why other options fail
Counting nodes with no neighbors or summing degrees won't give reachable count; BFS is alternative but not required.
Final Answer:
Add a counter variable incremented each time a node is visited during DFS -> Option A
Quick Check:
Count nodes when visited in DFS [OK]
Hint: Increment count inside DFS when visiting nodes [OK]
Common Mistakes:
Counting nodes with no neighbors instead of visited
Using BFS unnecessarily
Summing degrees instead of counting visited
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.