Code Snippets
/

Python BFS Template

Python BFS Template

Breadth-first search visits nodes in order of distance from the start, which makes it the right tool for shortest-path-by-edge-count, level-order traversal, and 'fewest steps' search problems. Python's `collections.deque` gives you O(1) `popleft`, which is the difference between BFS and an O(n^2) accident. This entry covers the standard template, distance tracking, and a level-by-level variant.

Python
Medium
3 snippets
bfs
graphs
algorithms
code-template

343 views

8

from collections import deque, defaultdict

def bfs(graph, start):
    """Return nodes in BFS visit order from `start`."""
    visited = {start}
    order = []
    queue = deque([start])
    while queue:
        node = queue.popleft()
        order.append(node)
        for nbr in graph[node]:
            if nbr not in visited:
                visited.add(nbr)
                queue.append(nbr)
    return order

# Build a small graph for the demo.
graph = defaultdict(list)
for u, v in [(1, 2), (1, 3), (2, 4), (3, 4), (4, 5), (5, 6)]:
    graph[u].append(v)
    graph[v].append(u)

print(bfs(graph, 1))   # e.g. [1, 2, 3, 4, 5, 6]
print(bfs(graph, 6))   # e.g. [6, 5, 4, 2, 3, 1]

# Single-node graph and disconnected start.
lonely = defaultdict(list)
lonely[42] = []
print(bfs(lonely, 42))  # [42]

BFS uses a FIFO queue: the first node enqueued is the first one dequeued. The crucial detail is marking a node visited when you enqueue it, not when you pop it; otherwise the same node can be enqueued many times by different neighbors. collections.deque gives O(1) popleft; using a plain list with pop(0) accidentally turns the algorithm into O(n^2) and is a top interview gotcha. The same loop body works for any iterable graph: dictionaries, adjacency matrices, or even on-the-fly neighbor functions.