JavaScript Snippet

BFS Traversal Template

Difficulty: Medium

Breadth-first search visits every reachable node in non-decreasing distance from the start, which makes it the right algorithm for shortest-path-in-unweighted-graph, level-order tree traversal, and grid-flood problems. This snippet covers the canonical queue + visited skeleton, the level-by-level form for tree-style problems, and the multi-source variant for problems like 'rotting oranges' where many start points share a frontier.

Code Snippets
/

BFS Traversal Template

BFS Traversal Template

Breadth-first search visits every reachable node in non-decreasing distance from the start, which makes it the right algorithm for shortest-path-in-unweighted-graph, level-order tree traversal, and grid-flood problems. This snippet covers the canonical queue + visited skeleton, the level-by-level form for tree-style problems, and the multi-source variant for problems like 'rotting oranges' where many start points share a frontier.

JavaScript
Medium
3 snippets
algorithms
bfs
code-template
queue

1,124 views

29

The canonical BFS keeps a Set of visited nodes and a queue of frontier nodes. Marking a node visited at the moment it enters the queue (not when it dequeues) is the easy mistake to avoid: forgetting to mark on enqueue can re-enqueue the same node many times and blow up runtime. Array.shift() is O(n) for large arrays; for big graphs use a real queue or an index-pointer trick (see next accordion). On small graphs the simplicity wins.