LOGBOOK

HELP

Quiz Entry - updated: 2026.11.27

Why can BFS work with a single first-in-first-out queue instead of separate level sequences?

Processing $L_i$ in order while appending to $L_{i+1}$ is exactly what one FIFO queue does: vertices of level i + 1 join at the back while level i is still being taken from the front, so all of level i leaves before any of level i + 1. The queue holds at most two adjacent levels at a time, and the levels can still be recovered by storing each vertex's distance.

The queue during BFS from A on the six-vertex graph: A, then B C D, then C D E, D E F, E F, F, empty, coloured by level

* B, C and D are all taken from the front before E and F, which joined later at the back. *

The queue version is the usual implementation:

Deque<Vertex<V>> queue = new ArrayDeque<>();
Map<Vertex<V>, Integer> dist = new HashMap<>();
queue.add(s);  dist.put(s, 0);
while (!queue.isEmpty()) {
  Vertex<V> v = queue.poll();                 // take from the front
  for (Edge<E> e : g.incidentEdges(v)) {
    Vertex<V> w = g.opposite(v, e);
    if (!dist.containsKey(w)) {               // not visited yet
      dist.put(w, dist.get(v) + 1);           // w lies in level dist(v) + 1
      queue.add(w);                           // join at the back
    }
  }
}

The queue has to be first-in-first-out. With a stack, the vertex added last would be processed first, and the search would run off in depth instead of going level by level. In Python, collections.deque with append and popleft is the right queue; a plain list's pop(0) shifts all remaining elements and costs $O(n)$ per removal.

Go deeper:

From Quiz: ADS / Graph Traversals: Depth-First and Breadth-First Search | Updated: Nov 27, 2026