Dev HelpersOpen library
← Back

Traverse a graph breadth-first

Traverse a graph breadth-first. A self-contained example using the Python standard library.

Open this example in the interactive library

Source code

from collections import deque
graph = {'a':['b','c'],'b':['d'],'c':[],'d':[]}
queue, seen, order = deque(['a']), {'a'}, []
while queue:
    node = queue.popleft()
    order.append(node)
    for child in graph[node]:
        if child not in seen:
            seen.add(child)
            queue.append(child)
print(order)

Sample output

['a', 'b', 'c', 'd']