📖 Scenario: You are working with a simple map of connected cities. Each city is connected to some other cities by roads. You want to find the order in which you can visit all cities starting from a specific city, using a method called Breadth First Search (BFS). BFS visits all neighbors of a city before moving to the next level of cities.
🎯 Goal: Build a program that uses BFS to visit all cities in the graph starting from a given city and prints the order of cities visited.
📋 What You'll Learn
Create a graph as a dictionary where keys are city names and values are lists of connected cities.
Create a queue to help with BFS traversal.
Implement BFS to visit cities level by level starting from a given city.
Print the order of cities visited by BFS.
💡 Why This Matters
🌍 Real World
BFS is used in social networks to find friends within certain degrees, in GPS navigation to find shortest routes, and in web crawlers to explore websites level by level.
💼 Career
Understanding BFS is essential for software engineers working on graph problems, network analysis, AI pathfinding, and many algorithmic challenges in interviews.
Progress0 / 4 steps
1
Create the graph dictionary
Create a dictionary called graph with these exact entries: 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E']
DSA Python
Hint
Use a dictionary where each key is a city and the value is a list of connected cities.
2
Set up BFS starting point and queue
Create a variable called start_city and set it to 'A'. Create a list called queue and initialize it with start_city. Create a set called visited and initialize it with start_city.
DSA Python
Hint
Use a list for queue and a set for visited to keep track of cities.
3
Implement BFS traversal
Create an empty list called order. Use a while loop that runs while queue is not empty. Inside the loop, remove the first city from queue and call it current_city. Append current_city to order. For each neighbor in graph[current_city], if the neighbor is not in visited, add it to visited and append it to queue.
DSA Python
Hint
Use a while loop and pop(0) to get the first city from the queue.
4
Print the BFS order
Print the order list to show the order of cities visited by BFS.
DSA Python
Hint
Use print(order) to display the BFS visit order.
Practice
(1/5)
1. What does BFS (Breadth First Search) primarily use to keep track of nodes to visit next in a graph?
easy
A. A dictionary to map nodes to their parents
B. A queue to explore nodes level by level
C. A set to store visited nodes only
D. A stack to explore nodes deeply
Solution
Step 1: Understand BFS traversal method
BFS explores nodes level by level, visiting all neighbors before moving deeper.
Step 2: Identify the data structure used
To achieve level order traversal, BFS uses a queue to store nodes to visit next.
Final Answer:
A queue to explore nodes level by level -> Option B
Quick Check:
BFS uses queue = D [OK]
Hint: BFS uses queue for level order traversal [OK]
Common Mistakes:
Confusing BFS with DFS which uses stack
Thinking BFS uses only a set without queue
Assuming BFS uses recursion instead of queue
2. Which of the following is the correct Python syntax to initialize a queue for BFS using collections module?
easy
A. queue = collections.deque()
B. queue = list()
C. queue = collections.Queue()
D. queue = set()
Solution
Step 1: Recall Python queue options for BFS
Python's collections module provides deque which supports fast append and pop from both ends.
Step 2: Identify correct initialization
collections.Queue() does not exist; list() is slower for queue operations; set() is unordered.
Final Answer:
queue = collections.deque() -> Option A
Quick Check:
Use deque for BFS queue = collections.deque() [OK]
Hint: Use collections.deque() for efficient BFS queue [OK]
Common Mistakes:
Using list() which is slow for queue operations
Trying collections.Queue() which is invalid
Using set() which is unordered
3. What is the output of the following BFS traversal starting from node 'A'?
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
from collections import deque
def bfs(graph, start):
visited = []
queue = deque([start])
while queue:
node = queue.popleft()
if node not in visited:
visited.append(node)
queue.extend(graph[node])
return visited
print(bfs(graph, 'A'))
medium
A. ['A', 'B', 'C', 'E', 'D', 'F']
B. ['A', 'C', 'B', 'F', 'D', 'E']
C. ['A', 'B', 'C', 'D', 'E', 'F']
D. ['A', 'B', 'C', 'D', 'F', 'E']
Solution
Step 1: Trace BFS starting from 'A'
Start with queue=['A'], visited=[]
- Pop 'A', visited=['A'], add neighbors 'B','C' to queue
- Pop 'B', visited=['A','B'], add 'D','E'
- Pop 'C', visited=['A','B','C'], add 'F'
- Pop 'D', visited=['A','B','C','D'], no neighbors
- Pop 'E', visited=['A','B','C','D','E'], add 'F'
- Pop 'F', visited=['A','B','C','D','E','F'], no neighbors
Step 2: Confirm order of visited nodes
The visited order is ['A', 'B', 'C', 'D', 'E', 'F'] as BFS explores level by level.
Final Answer:
['A', 'B', 'C', 'D', 'E', 'F'] -> Option C
Quick Check:
BFS order from 'A' = ['A', 'B', 'C', 'D', 'E', 'F'] [OK]
Hint: Follow queue pops and neighbor additions stepwise [OK]
Common Mistakes:
Mixing BFS with DFS order
Not checking if node already visited before adding
Assuming neighbors added in wrong order
4. Identify the bug in this BFS code snippet and choose the fix:
def bfs(graph, start):
visited = set()
queue = [start]
while queue:
node = queue.pop()
if node not in visited:
visited.add(node)
queue.extend(graph[node])
return list(visited)
medium
A. Change queue.pop() to queue.pop(0) to pop from front
B. Change visited to a list instead of set
C. Remove the if condition checking visited
D. Use queue.append(node) instead of extend
Solution
Step 1: Understand queue behavior in BFS
BFS requires FIFO order, so nodes must be popped from the front of the queue.
Step 2: Identify the bug in popping nodes
queue.pop() removes from the end (LIFO), which behaves like DFS. Changing to queue.pop(0) pops from front (FIFO).
Final Answer:
Change queue.pop() to queue.pop(0) to pop from front -> Option A
Quick Check:
Use pop(0) for BFS queue pop [OK]
Hint: BFS queue pops from front: use pop(0) [OK]
Common Mistakes:
Using pop() which pops from end (DFS behavior)
Confusing set and list for visited
Removing visited check causing infinite loops
5. Given a graph with possible cycles, how can BFS be modified to avoid infinite loops and correctly return the shortest path length from a start node to a target node?
hard
A. Use a stack instead of queue to track nodes
B. Use DFS instead of BFS to avoid cycles
C. Remove edges that form cycles before BFS
D. Use a visited set to track visited nodes and stop when target is found, counting levels
Solution
Step 1: Understand BFS with cycles
In graphs with cycles, BFS can revisit nodes infinitely unless visited nodes are tracked.
Step 2: Modify BFS to track visited and count levels
Use a visited set to avoid revisiting nodes and maintain a level count to find shortest path length. Stop BFS when target node is reached.
Final Answer:
Use a visited set to track visited nodes and stop when target is found, counting levels -> Option D
Quick Check:
Visited set + level count = shortest path BFS [OK]
Hint: Track visited nodes and levels to avoid cycles [OK]
Common Mistakes:
Using DFS which doesn't guarantee shortest path
Trying to remove cycles manually before BFS
Using stack which causes DFS behavior
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.