Python Snippet

Python BFS Template

Difficulty: Medium

Breadth-first search visits nodes in order of distance from the start, which makes it the right tool for shortest-path-by-edge-count, level-order traversal, and 'fewest steps' search problems. Python's `collections.deque` gives you O(1) `popleft`, which is the difference between BFS and an O(n^2) accident. This entry covers the standard template, distance tracking, and a level-by-level variant.

Code Snippets
/

Python BFS Template

Python BFS Template

Breadth-first search visits nodes in order of distance from the start, which makes it the right tool for shortest-path-by-edge-count, level-order traversal, and 'fewest steps' search problems. Python's `collections.deque` gives you O(1) `popleft`, which is the difference between BFS and an O(n^2) accident. This entry covers the standard template, distance tracking, and a level-by-level variant.

Python
Medium
3 snippets
bfs
graphs
algorithms
code-template

343 views

8

BFS uses a FIFO queue: the first node enqueued is the first one dequeued. The crucial detail is marking a node visited when you enqueue it, not when you pop it; otherwise the same node can be enqueued many times by different neighbors. collections.deque gives O(1) popleft; using a plain list with pop(0) accidentally turns the algorithm into O(n^2) and is a top interview gotcha. The same loop body works for any iterable graph: dictionaries, adjacency matrices, or even on-the-fly neighbor functions.