Skip to the content.

13. Graphs: Breadth-First Search (BFS)

Back to the index

Explore a graph in rings: first all neighbors, then their neighbors, using a queue. BFS finds the shortest path (fewest edges) in an unweighted graph.

How it works

Store the graph as an adjacency list: each node maps to the list of its neighbors. BFS starts from a source, puts it in a queue, and repeatedly takes the oldest node and enqueues every neighbor not seen yet.

Mark a node as seen when you enqueue it, not when you dequeue it, or the same node can enter the queue many times. Because nodes are dequeued in order of distance, the first time BFS reaches a node is along a shortest path.

Diagram

graph LR
    A --- B
    A --- C
    B --- D
    B --- E
    C --- F
    E --- F

Step-by-step trace

Input: Undirected graph with adjacency list A: B, C; B: A, D, E; C: A, F; D: B; E: B, F; F: C, E. BFS from A, neighbors in list order.

Step Dequeue Newly discovered (distance) Queue after Visit order
1 A B (1), C (1) [B, C] [A]
2 B D (2), E (2) [C, D, E] [A, B]
3 C F (2) [D, E, F] [A, B, C]
4 D none [E, F] [A, B, C, D]
5 E none [F] [A, B, C, D, E]
6 F none [] [A, B, C, D, E, F]

Result: Distances from A: A=0, B=1, C=1, D=2, E=2, F=2.

Complexity

Operation Time Space
BFS over V nodes and E edges O(V + E) O(V)
Grid of R x C cells O(R * C) O(R * C)

Python reference implementation

def bfs(graph, start):
    """Return (visit order, distance in edges) from start."""
    dist = {start: 0}
    order = []
    queue = deque([start])
    while queue:
        node = queue.popleft()
        order.append(node)
        for nb in graph[node]:
            if nb not in dist:          # mark when enqueued, not when visited
                dist[nb] = dist[node] + 1
                queue.append(nb)
    return order, dist

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Segment Tree (Range Sum Queries) Next: Graphs: Depth-First Search (DFS)