BFS and DFS traversals

Breadth-first search (BFS) explores a graph level by level, using a queue, and finds the shortest path in number of edges. Depth-first search (DFS) follows a branch to the end before backtracking, using a stack or recursion. Both visit each node while keeping track of those already seen.

Example

from collections import deque
def bfs(g, s):
    vus, f = {s}, deque([s])
    while f:
        n = f.popleft()
        for v in g[n]:
            if v not in vus:
                vus.add(v); f.append(v)

Related concepts

The whole glossary