Idiom #129 Breadth-first traversal in a graph
Call the function f on every vertex accessible from the vertex start, in breadth-first prefix order

def breadth_first(start, f):
seen = set()
q = deque([start])
while q:
vertex = q.popleft()
f(vertex)
seen.add(vertex)
q.extend(v for v in vertex.adjacent if v not in seen)
It's best to not recurse in Python when the structure size is unknown, since we have a fixed, small stack size.