Skip to main content
CodeFlow
all algorithms
algorithm 10

Breadth-First Search

Walk a graph in expanding rings. Visit every node at distance 1 before any node at distance 2.

ABCDEF

Pick a start node, then BFS or DFS, then Step.

What you just watched

BFS uses a queue (FIFO). Start by enqueuing the source node and marking it seen. Loop: dequeue the next node, enqueue any neighbours you haven't seen yet. Repeat until the queue is empty.

That FIFO order is what gives BFS its level-by-level shape. The first time you reach the target, you've traveled the fewest edges possible. That's why BFS finds the shortest path in number of hops on an unweighted graph.

Use BFS for: shortest path in unweighted graphs (mazes, social distance, friend-of-a-friend), level-by-level processing of trees, connected components.

from collections import deque

def bfs(graph, start):
    seen = {start}
    queue = deque([start])
    while queue:
        node = queue.popleft()
        process(node)
        for n in graph[node]:
            if n not in seen:
                seen.add(n)
                queue.append(n)