Ripples in a pond

Breadth-First Search

The analogy

Drop a stone in a pond. The ripple reaches everything one step away, then everything two steps away, then three. BFS explores a map the same way โ€” all your friends first, then all their friends โ€” which is why the first time it reaches a place, it got there by the shortest route.

Visualizer

Ripples across the map

step 1 / 14
ABCDEFGH

Start at A. A queue holds who to visit next โ€” first in, first out.Queue: A

๐Ÿ“– In depth โ€” the full reference

BFS โ€” everything worth knowing

factvaluenote
time / spaceO(V + E) / O(V)each node enqueued once, each edge looked at once (twice if undirected)
data structureQUEUE โ€” non-negotiableswap in a stack and it silently becomes DFS
guaranteefirst arrival = fewest EDGESshortest path in unweighted graphs โ€” its defining superpower
mark seen on ENQUEUEnot on dequeueelse a node enters the queue twice via two neighbours โ€” subtle classic bug
path recoverystore parent[child] = node when enqueueingwalk parents backward from the goal
weighted graphsBFS is NOT enoughfewest edges โ‰  cheapest path โ€” Dijkstra (Module 6) fixes this
level trackingprocess the queue one ring at a timefor level = len(queue) snapshots โ€” "minimum moves" problems

Python: the canonical BFS

from collections import deque

def bfs(adj, start):
    order = []
    seen = {start}                 # mark on enqueue!
    q = deque([start])
    while q:
        node = q.popleft()          # O(1) โ€” the deque lesson pays off
        order.append(node)
        for nb in adj[node]:
            if nb not in seen:
                seen.add(nb)
                q.append(nb)
    return order
# list.pop(0) here would make BFS itself O(V^2). deque or bust.
from collections import deque

def bfs(adj, start):
    seen = {start}
    q = deque([start])
    order = []
    while q:
        v = q.popleft()          # FIFO
        order.append(v)
        for w in adj[v]:
            if w not in seen:
                seen.add(w)
                q.append(w)
    return order
Check yourself

BFS uses which structure?

Practice โ€” write it yourself

bfs_order(adj, start): ripples with a QUEUE (pop from the front, append to the back). Mark seen on enqueue. Return the visit order.

Python 3 ยท runs in your browser ยท your draft is saved locally
๐Ÿ“ My notessaved in this browser