Trees and graphs · Intermediate
Breadth-first search and level order
Explore in rings around the start with a FIFO queue; the first time you reach a node is by a fewest-edges path, and one ring is one level.
On this page
The idea
A queue processes nodes in the order they were discovered. Starting from one node (or several), it finishes everything at distance 1 before anything at distance 2. That ordering is the whole proof that BFS finds shortest paths in unweighted graphs and grids.
Processing the queue one level at a time (read its size, then pop exactly that many) gives level-order traversal of a tree: per-level averages, right-side views, minimum depth.
How to recognise it
- Fewest moves, fewest steps, minimum number of edges, in an unweighted graph or grid.
- Anything per depth level of a tree.
- Spreading from several sources at once (multi-source BFS: rot, fire, distance to nearest exit).
When not to use it
- Edges have different non-negative weights: use Dijkstra (or 0-1 BFS when weights are only 0 and 1).
- You need to enumerate all paths or build an answer that depends on the whole path: DFS with backtracking fits better.
Template
Language-neutral pseudocode (Python-like). Adapt names and types to your language; the solved problems below have tested implementations in C#, Python, Java and C++.
dist = map {start: 0}
queue = deque([start])
while queue:
u = queue.pop_front()
for v in neighbours(u):
if v not in dist: # mark when enqueued, not when dequeued
dist[v] = dist[u] + 1
queue.push_back(v)
return dist
# Level by level (trees)
level = 0
while queue:
for _ in range(len(queue)):
node = queue.pop_front(); visit(node, level)
for child in node.children: queue.push_back(child)
level += 1- Mark a node visited when you enqueue it; marking on dequeue can enqueue the same node many times.
- Use a real queue (deque, ring buffer). Removing from the front of a dynamic array is O(n) per removal.
Complexity
Time O(V + E), extra space O(V). Each vertex is enqueued once and each edge examined once (twice for undirected graphs). A grid of r × c cells has V = rc and E ≤ 4rc.
Worked examples
Level order of a small tree
Root A with children B and C; B has child D. Queue [A] → level 0: A, enqueue B, C. Level 1: B (enqueue D), C. Level 2: D. Levels: [A], [B, C], [D].
Pitfalls
- Marking visited on dequeue.
- Using a list with pop(0) / remove(0) as the queue.
- Forgetting grid bounds or obstacles when generating neighbours.
Practise it
Solved problems with hints, a correctness argument and four tested implementations:
- ProblemFewest steps across a walled grid· intermediate · O(rows · columns)
- ProblemMinutes until the whole office knows· intermediate · O(rows · columns)
Learn the foundations
Lessons
- ModuleM24 BFS and DFS· intermediate
- ModuleM18 Trees· intermediate
- ModuleM09 Queues and Deques· beginner
- VisualizerTree traversal· Θ(n)
- VisualizerQueue (ring buffer)· enqueue/dequeue O(1)
- Collectioncollections.deque· Python
- CollectionQueue<T>· C#
- CollectionArrayDeque<E>· Java
- Collectionstd::deque<T>· C++
Related patterns
- PatternDepth-first search and backtracking· O(V + E) for graph DFS; O(2ⁿ) subsets, O(n!) permutations
- PatternTopological ordering· O(V + E)
References
dsa.pattern.bfs-level-order · version 1