4. The following BFS code for counting connected components has a bug. What is the error?
func countComponents(graph map[int][]int) int {
visited := make(map[int]bool)
count := 0
for node := range graph {
if visited[node] {
queue := []int{node}
visited[node] = true
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
for _, neighbor := range graph[current] {
if !visited[neighbor] {
visited[neighbor] = true
queue = append(queue, neighbor)
}
}
}
count++
}
}
return count
}
medium
A. The visited map is not initialized
B. The queue initialization is incorrect
C. The condition should be if !visited[node], not if visited[node]
D. The count variable is not incremented
Solution
Step 1: Analyze the if condition for BFS start
The code starts BFS only if visited[node] is true, which is wrong; it should start if node is not visited.
Step 2: Understand impact on BFS traversal
Because of wrong condition, BFS never starts, so count remains zero incorrectly.
Final Answer:
The condition should be if !visited[node], not if visited[node] -> Option C
Quick Check:
Start BFS on unvisited nodes [OK]
Hint: Start BFS only if node is unvisited [OK]
Common Mistakes:
Using visited[node] instead of !visited[node]
Not initializing visited map
Forgetting to increment count
5. You have a graph with nodes 0 to 6 and edges: (0-1), (1-2), (3-4), (5-6). Using BFS to find connected components, what is the count if node 7 is isolated and missing from the adjacency list?
Choose the correct approach to count all components including isolated nodes.
hard
A. Count only nodes connected by edges
B. Include node 7 in the graph map with empty adjacency list before BFS
C. Ignore node 7 since it is not in adjacency list
D. Add node 7 as connected to node 0
Solution
Step 1: Recognize isolated nodes must be in graph map
To count isolated nodes as components, they must appear in the graph with empty adjacency lists.
Step 2: Include node 7 with empty neighbors before BFS
Adding node 7 ensures BFS visits it as a separate component.
Final Answer:
Include node 7 in the graph map with empty adjacency list before BFS -> Option B
Quick Check:
Isolated nodes need empty adjacency list [OK]
Hint: Add isolated nodes with empty lists to graph before BFS [OK]
Common Mistakes:
Ignoring isolated nodes not in adjacency list
Assuming isolated nodes are counted automatically
Connecting isolated nodes incorrectly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.