Breadth-First Search (BFS) — Level Order on Graphs — Complete Beginner Guide
Learning Objectives
- Implement BFS with a queue
- Track visited vertices to avoid loops
- Measure distance in levels or hops
- Find shortest paths in unweighted graphs
- Analyze BFS time and space complexity
What Is BFS?
Breadth-first search explores a graph outward in waves. It visits the start vertex, then all neighbors, then their neighbors, and so on. The result is level order traversal on a graph.
A queue keeps the frontier in first-in first-out order so shallow nodes finish before deep nodes.
from collections import deque
def bfs(graph, start):
visited = set([start])
order = []
queue = deque([start])
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return order
graph = {
"A": ["B", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F"],
"D": ["B"],
"E": ["B", "F"],
"F": ["C", "E"],
}
print(bfs(graph, "A"))
# A, then B and C, then D E F
Why a Queue?
The queue holds vertices waiting to expand. Newly discovered neighbors go to the rear. That guarantees vertices closer to the start leave earlier than deeper vertices.
| Structure | Role in BFS |
|---|---|
| Queue | Frontier waiting for expansion |
| Visited set | Stops cycles and repeats |
| Distance map | Stores level of each vertex |
| Parent map | Rebuilds shortest path later |
Shortest Path in Unweighted Graphs
With unit edge costs, BFS distance equals the fewest edges. Record the distance when first discovered.
from collections import deque
def bfs_distances(graph, start):
dist = {start: 0}
parent = {start: None}
queue = deque([start])
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if neighbor not in dist:
dist[neighbor] = dist[node] + 1
parent[neighbor] = node
queue.append(neighbor)
return dist, parent
def path_to(parent, target):
out = []
current = target
while current is not None:
out.append(current)
current = parent[current]
out.reverse()
return out
dist, parent = bfs_distances(graph, "A")
print(dist["F"])
print(path_to(parent, "F"))
Level-by-Level Loop Variant
Sometimes you need levels as separate groups. Track the queue size at each layer.
from collections import deque
def levels(graph, start):
visited = set([start])
queue = deque([start])
result = []
while queue:
level_size = len(queue)
current_level = []
for _ in range(level_size):
node = queue.popleft()
current_level.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
result.append(current_level)
return result
print(levels(graph, "A"))
Complexity
| Metric | Cost | Reason |
|---|---|---|
| Time adjacency list | O(V plus E) | Visit vertices and edges once |
| Time adjacency matrix | O(V squared) | Scan full rows |
| Space | O(V) | Visited, queue, maps |
| Queue peak | Up to O(V) | Wide level |
V is the number of vertices and E is the number of edges.
When to Use BFS
- Shortest path in unweighted graphs
- Level order printing of a graph
- Finding neighbors within k steps
- Bipartite checking by two-coloring
- Web crawlers exploring by depth layer
- Solving mazes with fewest moves
BFS does not explore deeply early, so it is memory hungry on wide graphs. Depth-first search trades that for deeper dives.
BFS Dry Runs
Dry run BFS on a small graph before coding. Start at A with distance zero. Enqueue A. Dequeue A and discover B and C at distance one. Dequeue B and discover D and E at distance two. Dequeue C and discover F at distance two. Remaining nodes exit in that shallow order.
Write the queue contents after every step. If a node is marked visited only after dequeue, duplicates slip into the queue. Mark on discovery to avoid that classic bug.
| Step | Queue After Step | Distances Known |
|---|---|---|
| start | A | A0 |
| pop A | B C | A0 B1 C1 |
| pop B | C D E | plus D2 E2 |
| pop C | D E F | plus F2 |
Then vary the graph: add a back edge to create a cycle and confirm visited handling stops the loop. Add weights and remember BFS no longer finds the cheapest path. That boundary keeps your tool choice honest.
BFS Implementation Pitfalls
Four pitfalls account for most beginner BFS bugs.
First, mark visited when you enqueue, not when you dequeue. Otherwise the same node enters the queue from two parents and you duplicate work. Second, remember that unweighted BFS assumes every edge costs the same. Introduce a weight and you need Dijkstra instead.
Third, on directed graphs follow only outgoing edges. Reversing direction silently searches the wrong network. Fourth, for grid BFS encode coordinates carefully so neighbors do not walk off the board or revisit cells already claimed.
def neighbors4(r, c, rows, cols):
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
yield nr, nc
print(list(neighbors4(0, 0, 3, 3)))
Drill one grid problem and one plain graph problem. Together they cover the majority of BFS interview shapes.
Key Takeaways
💡
- BFS explores in waves using a first-in first-out queue
- Visited tracking prevents cycles and repeated work
- BFS gives shortest hop count on unweighted graphs
- Time is O(V plus E) with adjacency lists
- Use BFS for level order, fewest steps, and neighbor searches
Practice Questions
- Run BFS from A on a line graph A-B-C-D and list visit order with distances.
- Why must BFS mark vertices visited when they are enqueued rather than when dequeued?
- Modify the code to stop early once a target vertex distance is found.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions