📖 Scenario: Imagine you have a group of friends where some know each other directly or through other friends. We want to find all separate friend groups where everyone is connected somehow.
🎯 Goal: Build a program that finds all connected friend groups (connected components) in a network using Breadth-First Search (BFS).
📋 What You'll Learn
Create a graph as a dictionary with exact friend connections
Create a set to keep track of visited friends
Use BFS to find all connected friend groups
Print each connected group as a list
💡 Why This Matters
🌍 Real World
Finding connected groups in social networks, computer networks, or clusters of related data.
💼 Career
Understanding BFS and connected components is important for roles in software development, data analysis, and network engineering.
Progress0 / 4 steps
1
Create the graph of friends
Create a dictionary called graph with these exact connections: 1: [2, 3], 2: [1, 4], 3: [1], 4: [2], 5: [6], 6: [5]
DSA Python
Hint
Use a dictionary where keys are friend IDs and values are lists of connected friends.
2
Create a set to track visited friends
Create an empty set called visited to keep track of friends already checked
DSA Python
Hint
Use set() to create an empty set for visited friends.
3
Use BFS to find connected components
Write a function called bfs that takes a start node and uses a queue to find all connected friends. Inside the function, create a list called component to store connected friends. Use a while loop to visit nodes and add unvisited neighbors to the queue and visited set. Return the component list. Then, create an empty list called connected_components. Use a for loop with variable node to go through all keys in graph. If node is not in visited, call bfs(node) and append the result to connected_components.
DSA Python
Hint
Use a queue from collections.deque to visit nodes in BFS order.
4
Print the connected components
Print the connected_components list to show all friend groups found
DSA Python
Hint
The output shows two groups: one with friends 1, 2, 3, 4 and another with 5, 6.
Practice
(1/5)
1. What does the BFS algorithm help find in an undirected graph when used for connected components?
easy
A. All nodes reachable from a starting node forming one connected component
B. The shortest path between two nodes only
C. The maximum degree of any node in the graph
D. The total number of edges in the graph
Solution
Step 1: Understand BFS in graph context
BFS explores all nodes reachable from a given start node by visiting neighbors level by level.
Step 2: Connect BFS to connected components
Using BFS from an unvisited node finds all nodes in that node's connected component.
Final Answer:
All nodes reachable from a starting node forming one connected component -> Option A
Quick Check:
BFS finds connected components by exploring reachable nodes [OK]
Hint: BFS explores all nodes connected to start node [OK]
Common Mistakes:
Confusing BFS with shortest path only
Thinking BFS counts edges
Mixing BFS with node degree calculation
2. Which of the following is the correct way to initialize a queue for BFS in Python?
easy
A. queue = []
B. queue = dict()
C. queue = set()
D. queue = collections.deque()
Solution
Step 1: Identify BFS queue requirements
BFS requires a queue data structure to process nodes in FIFO order.
Step 2: Choose correct Python queue type
collections.deque() is efficient for queue operations (append and popleft).
Final Answer:
queue = collections.deque() -> Option D
Quick Check:
Use deque for BFS queue in Python [OK]
Hint: Use deque for efficient FIFO queue in BFS [OK]
Common Mistakes:
Using list which is inefficient for popping front
Using set which is unordered
Using dict which is key-value store
3. What is the output of the following code snippet that finds connected components using BFS?
graph = {0: [1], 1: [0, 2], 2: [1], 3: []}
visited = set()
components = []
for node in graph:
if node not in visited:
queue = collections.deque([node])
comp = []
while queue:
current = queue.popleft()
if current not in visited:
visited.add(current)
comp.append(current)
queue.extend(n for n in graph[current] if n not in visited)
components.append(sorted(comp))
print(components)
medium
A. [[0], [1], [2], [3]]
B. [[0, 1], [2, 3]]
C. [[0, 1, 2], [3]]
D. [[3], [0, 1, 2]]
Solution
Step 1: Analyze graph structure
Nodes 0,1,2 are connected; node 3 is isolated.
Step 2: Trace BFS for each component
Starting at 0, BFS visits 0,1,2; then 3 alone forms second component.
Final Answer:
[[0, 1, 2], [3]] -> Option C
Quick Check:
Connected components = [[0,1,2],[3]] [OK]
Hint: Group nodes reachable from each unvisited node [OK]
Common Mistakes:
Not sorting component lists
Mixing isolated node with others
Forgetting to mark visited nodes
4. Identify the bug in this BFS connected components code snippet:
def bfs_components(graph):
visited = set()
components = []
for node in graph:
if node not in visited:
queue = [node]
comp = []
while queue:
current = queue.pop()
if current not in visited:
visited.add(current)
comp.append(current)
for neighbor in graph[current]:
if neighbor not in visited:
queue.append(neighbor)
components.append(comp)
return components
medium
A. Using list pop() removes from end, not front, breaking BFS order
B. Visited set is not updated correctly
C. Neighbors are not checked for visited status
D. Components list is not returned
Solution
Step 1: Check queue operations
Using list pop() removes last element, making it DFS, not BFS.
Step 2: Understand BFS queue behavior
BFS requires FIFO, so pop(0) or deque.popleft() is needed.
Final Answer:
Using list pop() removes from end, not front, breaking BFS order -> Option A