The Queue in Breadth-First Search
BFS uses a FIFO queue so that vertices are expanded in discovery order, which is nondecreasing distance from the source; that ordering is what makes the first visit to a vertex its shortest path. A stack expands the newest vertex first, which produces depth-first search instead.
The short answer
Breadth-first search uses a first-in, first-out queue because the queue preserves discovery order, and discovery order is distance order. Every vertex discovered while expanding a vertex at distance d sits at distance d + 1, and appending it to the back of the queue places it behind all vertices already waiting at distance d. The traversal therefore finishes one distance layer before starting the next. Replace the queue with a stack and the most recently discovered vertex is expanded first, which is depth-first search.
A minimal example
from collections import deque
def bfs(graph, start):
dist = {start: 0}
q = deque([start])
while q:
u = q.popleft() # FIFO
for v in graph[u]:
if v not in dist:
dist[v] = dist[u] + 1
q.append(v) # mark visited on enqueue
return dist
The only change needed for depth-first search is the removal end:
stack = [start]
seen = {start}
while stack:
u = stack.pop() # LIFO
for v in graph[u]:
if v not in seen:
seen.add(v)
stack.append(v)
Why this happens
Consider the queue just before a vertex at distance d is dequeued. It contains only vertices at distance d or d + 1, in nondecreasing distance order. Expanding the distance-d vertex appends its undiscovered neighbors, all at distance d + 1, at the back, behind any distance-d vertices still queued. So all distance-d vertices are dequeued before the first distance-d + 1 vertex, and the claim holds by induction from the source at distance 0.
The first discovery of a vertex is also its shortest distance. It is discovered from a vertex at distance d, giving a path of length d + 1; if a shorter path existed, its predecessor at distance d - 1 or less would have been expanded earlier and discovered the vertex sooner. A stack has no such argument because it abandons the current layer as soon as a new neighbor appears.
Choosing the frontier
| Frontier | Traversal | Shortest paths, unweighted | Typical use |
|---|---|---|---|
| FIFO queue | BFS | Yes | Distance, connected components |
| LIFO stack | DFS | No | Cycle detection, topological order |
| Min-heap by distance | Dijkstra | Yes, weighted edges | Nonnegative weights |
| Deque, push front for weight 0 | 0-1 BFS | Yes, weights 0 and 1 | Binary-weight graphs |
Edge cases and practical checks
Mark a vertex visited when it is enqueued, not when it is dequeued. With dequeue-time marking, a vertex can enter the queue several times before its first turn, which inflates memory and can make distance updates confusing.
For multiple sources, seed the queue with all of them at distance 0; the same layering argument applies. For an implicit graph, such as a grid or a word-ladder puzzle, the queue still works; generate neighbors on expansion instead of storing edges. To recover a path rather than a distance, store a parent pointer when a vertex is first discovered and walk it backward from the target.
The complexity is O(V + E) with adjacency lists, assuming each membership test is O(1). The visited structure is usually a hash set, so the bound inherits the average-case behavior of hashing; average and worst-case hash table lookups explains when that assumption fails. Memory is O(V) for the visited set and up to O(V) for the frontier, which on a wide graph can be much larger than the depth of a DFS stack.
Sources
Revision history
- Published
- Updated
- — Initial publication.