Practice
Solution
Step 1: Trace the first iteration of the while loop
Initially, queue contains node 1. We pop node 1 and iterate over its neighbors: nodes 2 and 3.Step 2: Update visited and neighbors
Nodes 2 and 3 are not visited, so they are cloned and added to visited and queue. Then, the cloned node 1's neighbors list is appended with cloned nodes 2 and 3 in order.Final Answer:
Option A -> Option AQuick Check:
Neighbors of cloned node 1 after first iteration are clones of nodes 2 and 3 [OK]
- Assuming neighbors list is empty after first iteration
- Mixing up order of neighbors appended
Solution
Step 1: Each cell is enqueued at most once because distance is updated only when -1.
Thus, BFS processes O(n^2) cells.Step 2: Each cell has up to 4 neighbors checked, so total operations are O(4*n^2) = O(n^2).
Initialization is also O(n^2), so total complexity is O(n^2) + O(n^2) = O(n^2).Final Answer:
Option A -> Option AQuick Check:
Multi-source BFS runs in linear time relative to grid size including initialization [OK]
- Assuming BFS runs from each land cell separately
- Counting neighbors multiple times incorrectly
- Confusing initialization cost with BFS cost
V courses and E prerequisite pairs?Solution
Step 1: Identify operations on nodes and edges
Each node is enqueued and dequeued once; each edge is visited once when decrementing in-degree.Step 2: Combine to get total complexity
Total time is proportional to number of nodes plus number of edges -> O(V + E).Final Answer:
Option A -> Option AQuick Check:
Standard BFS topological sort runs in linear time relative to graph size [OK]
- Assuming nested loops cause O(V*E)
- Confusing dense graph worst case with typical complexity
- Ignoring that BFS processes nodes once
Solution
Step 1: Add diagonal neighbors to the neighbor list
Include all 8 directions: horizontal, vertical, and diagonal neighbors.Step 2: Mark cells as visited when enqueuing
This prevents adding the same cell multiple times from different neighbors, avoiding double counting.Step 3: Keep BFS traversal logic unchanged otherwise
Running BFS twice or switching to DFS is unnecessary and inefficient.Final Answer:
Option D -> Option DQuick Check:
Mark visited on enqueue avoids duplicates with expanded neighbors [OK]
- Not marking visited on enqueue causing duplicates
- Running BFS multiple times unnecessarily
- Thinking BFS can't handle diagonals
Solution
Step 1: Consider space usage of BFS queue
BFS queue can grow large if many 'O's are connected; marking visited in-place helps avoid revisiting.Step 2: Prune BFS early when no new 'O's are found
This reduces unnecessary queue growth and improves space efficiency without losing correctness.Final Answer:
Option C -> Option CQuick Check:
In-place marking plus pruning optimizes BFS space [OK]
- Using DFS recursion can cause stack overflow on large boards.
- Not marking visited cells causes infinite loops or revisits.
- Running BFS from every 'O' is inefficient and unnecessary.
