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,125 views

29

function bfs(start, getNeighbors) {
    const visited = new Set([start]);
    const queue = [start];
    const order = [];
    while (queue.length > 0) {
        const node = queue.shift();
        order.push(node);
        for (const next of getNeighbors(node)) {
            if (visited.has(next)) continue;
            visited.add(next);
            queue.push(next);
        }
    }
    return order;
}

const graph = { A: ['B', 'C'], B: ['D'], C: ['D', 'E'], D: [], E: [] };
console.log(bfs('A', (n) => graph[n])); // [A, B, C, D, E]

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.