Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
BFS Traversal and Applications
📖 Scenario: Imagine you are exploring a city with many connected streets and intersections. You want to visit all places starting from your home, moving step-by-step to the nearest unvisited places first.
🎯 Goal: You will build a simple representation of a city map as a graph, set up a starting point, perform a Breadth-First Search (BFS) traversal to visit all connected places, and finally identify the order in which places are visited.
📋 What You'll Learn
Create a graph using a dictionary where keys are place names and values are lists of connected places.
Set a starting place for BFS traversal.
Implement BFS traversal using a queue to visit places level by level.
Record the order of places visited during BFS.
💡 Why This Matters
🌍 Real World
BFS is used in real life to explore networks like social connections, city maps, or computer networks to find the shortest path or to visit all connected nodes.
💼 Career
Understanding BFS is important for roles in software development, data analysis, and network engineering where graph traversal and search algorithms are common.
Progress0 / 4 steps
1
Create the city map graph
Create a dictionary called city_map with these exact entries: 'Home': ['Park', 'Mall'], 'Park': ['Home', 'School'], 'Mall': ['Home', 'Cinema'], 'School': ['Park'], 'Cinema': ['Mall'].
Data Structures Theory
Hint
Think of city_map as a dictionary where each place points to a list of places directly connected to it.
2
Set the starting place for BFS
Create a variable called start_place and set it to the string 'Home'.
Data Structures Theory
Hint
The BFS traversal needs a starting point. Use the exact variable name start_place and assign it the string 'Home'.
3
Implement BFS traversal
Write code to perform BFS traversal starting from start_place. Create a list called visited to record visited places, a list called queue initialized with start_place, and use a while loop to visit places. In each loop, remove the first place from queue, add it to visited, then add its unvisited neighbors from city_map to queue.
Data Structures Theory
Hint
Use a queue (list) to keep track of places to visit next. Always visit the first place in the queue, mark it visited, then add its neighbors if not visited.
4
Record and finalize BFS visit order
Ensure the list visited contains the order of places visited by BFS starting from start_place. This list represents the BFS traversal order of the city map.
Data Structures Theory
Hint
The visited list holds the order in which places were visited by BFS. This completes the BFS traversal.
Practice
(1/5)
1. What is the main data structure used in BFS (Breadth-First Search) traversal of a graph?
easy
A. Queue
B. Stack
C. Priority Queue
D. Hash Map
Solution
Step 1: Understand BFS traversal method
BFS explores nodes level by level, which requires processing nodes in the order they are discovered.
Step 2: Identify the suitable data structure
A queue follows First-In-First-Out (FIFO) order, perfect for level-wise exploration in BFS.
Final Answer:
Queue -> Option A
Quick Check:
BFS uses a queue = Queue [OK]
Hint: BFS uses FIFO order, so it needs a queue [OK]
Common Mistakes:
Confusing BFS with DFS which uses a stack
Thinking BFS uses a priority queue
Assuming BFS uses a hash map as main structure
2. Which of the following is the correct way to mark a node as visited in BFS to avoid revisiting it?
easy
A. Add node to a stack after visiting
B. Add node to a visited set or list immediately when enqueued
C. Add node to the queue only after processing all neighbors
D. Do not mark nodes; revisit all nodes
Solution
Step 1: Understand when to mark nodes visited in BFS
Nodes should be marked visited when they are enqueued to prevent multiple enqueues of the same node.
Step 2: Identify correct marking method
Adding nodes to a visited set immediately when enqueued ensures no duplicates in the queue.
Final Answer:
Add node to a visited set or list immediately when enqueued -> Option B
Quick Check:
Mark visited on enqueue = Add node to a visited set or list immediately when enqueued [OK]
Hint: Mark nodes visited when enqueued, not after dequeued [OK]
Common Mistakes:
Marking nodes visited only after dequeuing
Using a stack instead of a visited set
Not marking nodes visited at all
3. Consider the following graph edges: 0 - 1, 0 - 2, 1 - 3, 2 - 3 If BFS starts at node 0, what is the order of nodes visited?
medium
A. [0, 1, 2, 3]
B. [0, 2, 1, 3]
C. [0, 3, 1, 2]
D. [1, 0, 2, 3]
Solution
Step 1: Start BFS from node 0
Enqueue 0, visited order starts with 0.
Step 2: Enqueue neighbors of 0 in order
Neighbors are 1 and 2, enqueue 1 then 2.
Step 3: Dequeue 1 and enqueue its neighbor 3
3 is neighbor of 1, enqueue 3.
Step 4: Dequeue 2, neighbor 3 already visited
No new nodes added.
Step 5: Dequeue 3, no new neighbors
Traversal ends.
Final Answer:
[0, 1, 2, 3] -> Option A
Quick Check:
BFS order = [0, 1, 2, 3] [OK]
Hint: Visit neighbors in order they appear, enqueue before dequeue [OK]
Common Mistakes:
Visiting neighbors in wrong order
Adding nodes multiple times
Starting BFS from wrong node
4. The following BFS code snippet has a bug. What is the error?
visited = set()
queue = [start]
visited.add(start)
while queue:
node = queue.pop()
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
visited.add(neighbor)
medium
A. Not marking start node as visited before loop
B. Queue should be a stack for BFS
C. Visited nodes added after enqueueing neighbors
D. Using pop() removes from the end, causing DFS behavior
Solution
Step 1: Analyze queue operations
pop() without argument removes last element, making it LIFO (stack), not FIFO (queue).
Step 2: Understand BFS requires FIFO
BFS needs to remove from front (pop(0)) to process nodes level by level.
Final Answer:
Using pop() removes from the end, causing DFS behavior -> Option D
Quick Check:
pop() without index = DFS, not BFS [OK]
Hint: Use pop(0) for queue behavior in BFS [OK]
Common Mistakes:
Using pop() instead of pop(0)
Forgetting to mark start node visited
Confusing stack and queue roles
5. You want to find the shortest path in an unweighted graph from node A to node B using BFS. Which of the following modifications is necessary to track the actual path?
hard
A. Run BFS twice, once from A and once from B, then combine results
B. Use a stack instead of a queue to track the path
C. Store each node's parent when enqueuing it, then backtrack from B to A
D. Mark nodes visited only after dequeuing them
Solution
Step 1: Understand BFS finds shortest path length
BFS explores nodes level by level, so the first time B is found is shortest path length.
Step 2: Track path by storing parents
When a node is enqueued, record which node led to it (its parent). After BFS, backtrack from B to A using parents.
Final Answer:
Store each node's parent when enqueuing it, then backtrack from B to A -> Option C
Quick Check:
Parent tracking + backtrack = shortest path [OK]
Hint: Save parents on enqueue, backtrack from target [OK]