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
  1. The idea
  2. How to recognise it
  3. When not to use it
  4. Template
  5. Complexity
  6. Worked examples
  7. Pitfalls
  8. Practise it
  9. Learn the foundations
  10. References

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:

Learn the foundations

Related patterns

References

dsa.pattern.bfs-level-order · version 1