CS Glossary
Breadth-First Search (BFS)
A graph/tree traversal that explores all neighbors at the current depth before moving to the next level, using a queue.
Overview
Breadth-First Search (BFS) explores a graph or tree level by level. It starts at a source node, visits all its neighbors, then visits all neighbors of those neighbors, and so on. BFS uses a queue (FIFO) to maintain the frontier of nodes to visit. It is the standard algorithm for finding the shortest path in unweighted graphs — the first time you reach a node via BFS, you have found the shortest path to it.
How It Works
- 1 Initialize a queue with the starting node and mark it as visited.
- 2 Dequeue the front node and process it (check if it is the target, record its level, etc.).
- 3 Enqueue all unvisited neighbors of the dequeued node and mark them as visited.
- 4 Repeat steps 2-3 until the queue is empty or the target is found.
- 5 For level-order traversal, process nodes level by level by tracking the queue size at each level.
Complexity Analysis
Each vertex is enqueued and dequeued at most once (O(V)), and each edge is examined at most once (O(E)). The queue stores at most V vertices at any time, giving O(V) space.
When to Use
- →Finding the shortest path in an unweighted graph
- →Level-order traversal of a binary tree
- →Finding connected components in a graph
- →Solving "minimum steps" or "minimum moves" problems (e.g., rotting oranges)
- →Bipartiteness checking (two-coloring)
- →Web crawling and social network analysis
Common Mistakes
- ⚠Forgetting to mark nodes as visited when enqueuing (not when dequeuing)
- ⚠Using DFS (stack/recursion) instead of BFS when shortest path is needed
- ⚠Not handling disconnected components (need to loop over all nodes)
- ⚠Forgetting to track levels for level-order problems
- ⚠Enqueuing the same node multiple times before it is visited
Code Examples
List<Integer> bfs(List<List<Integer>> graph, int start) {
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();
visited.add(start);
queue.add(start);
List<Integer> order = new ArrayList<>();
while (!queue.isEmpty()) {
int node = queue.poll();
order.add(node);
for (int neighbor : graph.get(node)) {
if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.add(neighbor);
}
}
}
return order;
} Related Patterns
Practice Problems
| Number of Islands | Medium |
| Rotting Oranges | Medium |
| Binary Tree Level Order Traversal | Medium |
| Course Schedule | Medium |
Frequently Asked Questions
What is BFS and when should I use it?
What is the difference between BFS and DFS?
How do I implement BFS for level-order traversal?
Master this concept with practice
Browse all patterns and problems to build systematic interview intuition.