BFS
Breadth-first search (BFS) visits a graph level by level: all neighbours of the start, then their neighbours, and so on. A queue holds the frontier. It finds shortest paths in unweighted graphs.
Detailed Explanation
DFS dives down one path. BFS spreads out. From a start node you enqueue its neighbours. You dequeue the oldest node, enqueue its unseen neighbours, and repeat. The first time you reach a node is the fewest edges from the start. That is why BFS is the default for "shortest route in a maze" and "degrees of separation".
The queue is a deque. pop(0) on a list makes BFS accidentally O(n²) in the frontier size. popleft is O(1). Mark a node seen when you enqueue it, not when you dequeue, or you will enqueue the same node many times from different parents.
Store parent pointers or distances in a dict if you need the path, not just reachability. Reconstruct by walking parents from the target back to the start, then reverse.
BFS works on implicit graphs: a word ladder where neighbours are words one letter away, a grid where neighbours are four cells. You do not build the full adjacency list if you can compute neighbours on the fly. You still need a seen set of states. The state must include everything that affects future moves (position plus remaining keys, for example).
Level-order trees are BFS. queue.Queue is for threads, not for this. Recursion is the wrong tool; the call stack would be DFS.
Weighted edges break the "first visit is shortest" proof. Use Dijkstra (heapq) when costs differ.
Code Examples
from collections import deque
def bfs(graph: dict[str, list[str]], start: str) -> list[str]:
seen = {start}
q = deque([start])
order = []
while q:
node = q.popleft()
order.append(node)
for nxt in graph.get(node, []):
if nxt not in seen:
seen.add(nxt)
q.append(nxt)
return order
g = {"a": ["b", "c"], "b": ["d"], "c": ["d"], "d": []}
print(bfs(g, "a")) # ['a', 'b', 'c', 'd']def shortest(graph: dict[str, list[str]], start: str, goal: str) -> list[str] | None:
parent = {start: None}
q = deque([start])
while q:
node = q.popleft()
if node == goal:
path = []
while node is not None:
path.append(node)
node = parent[node]
path.reverse()
return path
for nxt in graph.get(node, []):
if nxt not in parent:
parent[nxt] = node
q.append(nxt)
return NoneCommon Gotchas
`list.pop(0)` for the frontier
use `deque.popleft`.
Marking seen on dequeue
the same node can sit in the queue many times. Mark on enqueue.
Unweighted only
a cheaper longer path exists when weights differ. Switch to Dijkstra.
Grids explode if state is only coordinates
add the extra bits of state (keys, remaining jumps) to `seen`.