Breadth-first search
广度优先搜索
Use a FIFO frontier to find a minimum-edge path, prove the layer invariant, and handle cycles without duplicate work.
breadth-first-searchSearch one step away before searching two steps away
A station map shows connections but no travel times. You want the fewest connections from S to G. Explore every station one connection from S, then every station two connections away, and continue outward. The first discovery of G has a minimum number of edges.
Breadth-first search, or BFS, implements this order with a first-in, first-out queue. Newly discovered states join the back; the next state to expand comes from the front. This discipline matters more than whether the diagram looks wide or narrow.
The queue preserves distance layers
For an unweighted graph, define as the minimum number of edges from the start to . Set the start’s discovered distance to zero. When expanding a state at distance , assign each previously unseen neighbor distance and enqueue it.
The queue contains states in nondecreasing discovered distance. Initially this is true. Removing the front cannot break the order, and newly enqueued states lie in the next layer. Suppose a first-discovered neighbor actually had a shorter path. Its predecessor on that shorter path would lie in an earlier layer, which would already have been expanded and discovered the neighbor—a contradiction. CS188, Uninformed Search
This proves minimum edge count. If every edge has the same positive cost , minimizing edge count also minimizes cost:
If edge costs differ, the equivalence disappears. One edge costing 10 can be worse than two edges costing 1 each. BFS would still prefer the one-edge route. Use uniform-cost search when nonnegative edge costs matter.
A graph implementation should mark a state discovered when enqueuing it. Waiting until expansion allows several parents to enqueue the same state. AIMA’s graph-search implementation also checks explored and frontier membership; the implementation below uses the parent dictionary for both membership and reconstruction. AIMA Python, breadth_first_graph_search
One dictionary can store discovery and the return route
This complete example uses finite adjacency lists and hashable vertex IDs. A missing adjacency entry means no outgoing edges. It returns a vertex list for a found path, including both endpoints, or None for an unreachable goal. An empty path is not used to mean failure because starting at the goal is a valid zero-edge solution.
from collections import deque
def bfs(graph, start, goal):
parent = {start: start}
queue = deque([start])
if start == goal:
return [start]
while queue:
u = queue.popleft()
for v in graph.get(u, []):
if v in parent:
continue
parent[v] = u
if v == goal:
path = [v]
while path[-1] != start:
path.append(parent[path[-1]])
return path[::-1]
queue.append(v)
return None
graph = {'S':['A','B'], 'A':['S','G'], 'B':['G'], 'G':[]}
assert bfs(graph,'S','G') == ['S','A','G']
assert bfs(graph,'S','S') == ['S']
assert bfs(graph,'S','missing') is None
assert bfs({'S':['S']},'S','G') is None
assert bfs({'S':['G','A'],'A':['G']},'S','G') == ['S','G']
assert bfs({None:[0],0:['end']},None,'end') == [None,0,'end']
In the example, both S–A–G and S–B–G have two edges. The adjacency order selects A first, so that is the returned path. BFS guarantees optimal edge count, not a unique route or a preferred alphabetical order.
Each reachable vertex is enqueued at most once and each outgoing edge is inspected at most once. With adjacency lists and expected constant-time dictionary operations, the work is ; the queue and parent map use extra space. Reconstructing a path of length takes time. These bounds refer to the reachable portion processed, apart from the already supplied graph storage.
Finite graphs and infinite search trees need different statements
On a finite graph, duplicate detection ensures the queue eventually empties or finds the goal. On an infinite implicit graph, BFS still finds a goal at finite depth when each expansion has finitely many successors and finishes in finite time. Infinite branching can prevent completion of even one layer. If no goal exists in an infinite space, BFS need not terminate.
For a search tree with branching factor bounded by and shallowest goal depth , testing goals on generation, as here, visits nodes in the worst case. A variant that tests only when removing nodes may generate part of depth before reaching the goal, giving a different common bound. State which implementation is being analyzed rather than treating these formulas as contradictory.
Memory is often the practical limit: the frontier can hold an entire broad layer. Iterative deepening reduces stored frontier size while repeating expansions. Bidirectional search can help when the goal and reverse transitions are available, but requires a correct meeting and stopping rule.
Check the queue, then check the objective
- Why mark a vertex when it enters the queue? Answer: to prevent multiple parents from scheduling the same vertex before its first expansion.
- What does the function return when start equals goal? Answer: a one-vertex path, representing zero edges.
- If S–G costs 10 and S–A–G costs 2, which route does BFS favor? Answer: S–G, because it has fewer edges; it is not the least-cost route.
- Does a cycle S–A–S cause this implementation to loop forever? Answer: no. Both vertices are marked at discovery and enqueued at most once.
A distance primitive with broad uses
BFS is useful for connectivity, minimum-hop routing, and distance layers in unweighted graphs. It also serves as a baseline for evaluating more informed search. A heuristic method should be compared on solution cost as well as expanded states; expanding fewer states is not an improvement if the returned route violates the task’s objective.
Make a prediction, then check
One edge costs 10; a two-edge route costs 2. What does BFS guarantee?
Learning objectives
- Prove minimum edge count at first discovery using the queue invariant.
- Implement duplicate detection and path reconstruction, distinguishing finite-graph and infinite-tree conditions.
Prerequisites & connections
Explore related knowledge →References
- CS188 Textbook — Uninformed Search
UC Berkeley CS188 course contributors - AIMA Python — search algorithms (commit f104e03, 2026-06-30)
AIMA Python contributors · 2026
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Re-derived the queue-layer invariant; on 60 seeded finite graphs, every target matched the minimum edge count from exhaustive simple-path enumeration.
- Executed identical endpoints, unreachable goals, self-loops, mixed vertex types, and path ties; separated finite-graph O(V+E) bounds from generation-time versus pop-time goal tests in trees.
- Compared arguments, modeling assumptions, numbers, and exercise answers across languages; structural checks separately compare display formulas, code, references, and main sections. No independent human peer review.
Source locations checked:
- CS188 Textbook — Uninformed Search · §1.3.2: BFS queue, equal-cost optimality, completeness; article explicitly qualifies infinite-space conditions
- AIMA Python — search algorithms (commit f104e03, 2026-06-30) · breadth_first_graph_search, fixed commit f104e03; compared enqueue-time duplicate handling
Related topics