Breadth-First Search (BFS)

BFS uses a queue to expand nodes layer by layer according to their edge distance from the start node, yielding the fewest-edge path in unweighted graphs or graphs with uniform positive edge weights. Marking nodes upon enqueueing prevents redundant expansion.

One-Line Definition

BFS uses a queue to expand nodes layer by layer according to their edge distance from the start node, yielding the fewest-edge path in unweighted graphs or graphs with uniform positive edge weights. Marking nodes upon enqueueing prevents redundant expansion.

Why It Matters

  • Unweighted shortest path: Finding the minimum steps in a maze, degrees of separation in a social network, or crawling web pages layer by layer.
  • Level-order traversal of a binary tree is BFS (see k2.ds.binary-tree).
  • It is a special case of Dijkstra's algorithm: when all edge weights are equal, Dijkstra reduces to BFS (see k2.algo.dijkstra).

Scope & Boundaries

The O(V+E)O(V+E) bound applies to standard graph traversal using an adjacency list where each node enters the queue at most once; in implicit state spaces, the number of nodes can grow exponentially. While BFS and equal-weight Dijkstra produce identical distance results, their implementations and runtime overhead are not the same.

How It Works / Diagram

Figure 1
Figure 2

Time complexity O(V+E)O(V+E): each vertex is enqueued once, and each edge is inspected once.

One of the earliest descriptions of BFS appears in E. F. Moore's 1959 paper on finding the shortest path through a maze; overview: https://en.wikipedia.org/wiki/Breadth-first_search

Runnable Example

Shortest path in a grid maze (including path reconstruction and ASCII visualisation) and degrees of separation in a social network (first-draft run log on Python 3.15.0):

# File: examples/22_bfs.py
# Breadth-First Search (BFS): expand outward ring by ring using a queue. Finds the shortest path in unweighted graphs
from collections import deque

grid = ["S.#.....",
        ".##.###.",
        "....#...",
        ".##...#G"]
R, C = len(grid), len(grid[0])
start = next((r, c) for r in range(R) for c in range(C) if grid[r][c] == "S")
goal = next((r, c) for r in range(R) for c in range(C) if grid[r][c] == "G")

def bfs(start, goal):
    q, parent = deque([start]), {start: None}
    order = 0
    while q:
        cur = q.popleft(); order += 1
        if cur == goal: break
        r, c = cur
        for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
            if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] != "#" and (nr, nc) not in parent:
                parent[(nr, nc)] = cur; q.append((nr, nc))
    path, p = [], goal
    while p: path.append(p); p = parent.get(p)
    return path[::-1], order

path, visited = bfs(start, goal)
print(f"Shortest path length: {len(path)-1} steps, dequeued {visited} cells in total")
canvas = [list(row) for row in grid]
for r, c in path[1:-1]: canvas[r][c] = "*"
print("\n".join("".join(row) for row in canvas))

# Social network: degrees of separation (layer-by-layer BFS)
friends = {"You": ["A", "B"], "A": ["C"], "B": ["C", "D"], "C": ["E"], "D": [], "E": []}
dist, q = {"You": 0}, deque(["You"])
while q:
    u = q.popleft()
    for v in friends[u]:
        if v not in dist: dist[v] = dist[u] + 1; q.append(v)
print("Degrees of separation:", dist)

First-draft retained output:

Shortest path length: 12 steps, dequeued 21 cells in total
S.#.....
*##.###.
****#***
.##***#G
Degrees of separation: {'You': 0, 'A': 1, 'B': 1, 'C': 2, 'D': 2, 'E': 3}

In the diagram, * marks the 12-step shortest path found by BFS, and # denotes walls. BFS dequeued only 21 cells before reaching the goal.

Common Misconceptions

  • Marking nodes as visited only upon dequeueing: The same node may be enqueued multiple times, wasting time or even exhausting memory; always mark nodes when enqueueing.
  • Using list.pop(0) as a queue: This takes O(n)O(n) time; use deque.popleft() instead.
  • Using BFS for shortest paths on weighted graphs: BFS counts only edges and ignores edge weights, producing incorrect results on weighted graphs (see k2.algo.shortest-path for examples).
  • Forgetting to record predecessor nodes: You will only get the distance and cannot reconstruct the actual path.

Relevance to AI Development

  • Multi-hop retrieval in knowledge graphs: Expanding 1-hop and 2-hop neighbours from an entity to build candidate context for GraphRAG.
  • Web crawling and data collection: Fetching pages layer by layer (always respect robots.txt and site terms of service).
  • Agent search: Enumerating tool calls or states layer by layer within a bounded step budget to find the shortest action sequence.
  • Dependency analysis: Identifying all downstream components affected by a module change through layer-by-layer propagation.

Further Reading

Comprehension Check

Under what condition does the path with the fewest edges also correspond to the path with the shortest travel time?

Reference answer: Every edge must represent the same positive time cost; when edge weights differ, switch to an appropriate weighted shortest-path algorithm.

Verification & Reproduction

Verification date: 2026-10-14. Example status: Passed. Run log for this round: 22_bfs.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram