Hint: Visit neighbors in enqueue order, process queue FIFO [OK]
Common Mistakes:
Visiting neighbors in wrong order
Visiting node 3 before 2
Adding duplicates of node 4
4. What is the error in this BFS code snippet in C#?
var queue = new Queue<int>();
var visited = new HashSet<int>();
queue.Enqueue(1);
while(queue.Count > 0) {
int node = queue.Dequeue();
if(!visited.Contains(node)) {
visited.Add(node);
foreach(var neighbor in graph[node]) {
queue.Enqueue(neighbor);
}
}
}
medium
A. Dequeue method is incorrect
B. Visited nodes are never added
C. Neighbors are enqueued even if already visited
D. Queue is not initialized
Solution
Step 1: Analyze neighbor enqueue logic
Neighbors are enqueued without checking if visited, causing duplicates.
Step 2: Identify missing visited check before enqueue
Should check if neighbor is visited before enqueue to avoid repeated processing.
Final Answer:
Neighbors are enqueued even if already visited -> Option C
Quick Check:
Check visited before enqueue = D [OK]
Hint: Check visited before enqueue to avoid duplicates [OK]
Common Mistakes:
Enqueueing visited neighbors multiple times
Not adding nodes to visited set
Incorrect queue initialization
5. You want to find the shortest path from node 1 to node 5 in an unweighted graph using BFS. Which modification is needed to the BFS algorithm to track the path?
hard
A. Mark nodes as visited only after dequeuing
B. Maintain a dictionary to store each node's parent during traversal
C. Use a stack instead of a queue to track nodes
D. Enqueue nodes multiple times to find all paths
Solution
Step 1: Understand BFS for shortest path
BFS finds shortest paths in unweighted graphs by exploring neighbors level-wise.
Step 2: Track path using parent dictionary
Store each node's parent when first visited to reconstruct path after BFS completes.
Final Answer:
Maintain a dictionary to store each node's parent during traversal -> Option B
Quick Check:
Parent tracking dictionary = C [OK]
Hint: Track parents to reconstruct shortest path after BFS [OK]
Common Mistakes:
Using stack breaks BFS order
Marking visited too late causes duplicates
Enqueueing nodes multiple times wastes time
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.