BFS
Breadth-first search visits a graph level by level using a queue. The first time you reach a node in an unweighted graph is a shortest path in number of edges.
Detailed Explanation
BFS starts at a source, visits its neighbours, then their neighbours, and so on. The structure that keeps this order is a queue: enqueue neighbours you have not seen, dequeue the next node to expand. A visited set (or a dist map) prevents revisiting. Without it, a cycle loops forever.
On an adjacency list, time is O(n + m) for n nodes and m edges: each node is enqueued once, each edge is looked at a constant number of times. Space is O(n) for the queue and the visited set in the worst case (a star, or the last level of a wide tree).
The shortest-path claim is only for unweighted edges (or all weights equal). The first time you pop a node, you have used the fewest edges. If edges have weights, use Dijkstra (a heap) or Bellman-Ford. A 0-1 BFS is a deque special case.
BFS also models "minimum moves" on implicit graphs: a word ladder (each word is a node, one-letter changes are edges), a grid (cells are nodes, four-neighbour steps are edges), a lock with digits. You do not store the whole graph; you generate neighbours from the current state.
A queue in JavaScript is an array with push and shift. shift is O(n). For contest-sized graphs that can be tens of thousands of nodes, use an index pointer (head++) on an array, or a two-stack queue, so dequeue is amortised O(1).
Multi-source BFS enqueues several starts at distance 0 (rotting oranges, nearest water). The same loop works.
What it costs you: memory on wide levels, and a wrong visited-timing. Mark visited when you enqueue, not when you dequeue, or you will enqueue the same node many times from different parents. Also, forgetting isolated nodes if you only start from one source in a disconnected graph.
Reach for BFS for shortest unweighted paths, level-order tree walks, and minimum-step puzzles. Reach for DFS when you need a path existence, a cycle in a directed graph (recursion stack), or a topological feel. Reach for Dijkstra when distances have weights.
Code Examples
function bfs(adj, start) {
const visited = new Set([start]);
const queue = [start];
const order = [];
let head = 0;
while (head < queue.length) {
const node = queue[head];
head += 1;
order.push(node);
for (const next of adj.get(node) ?? []) {
if (visited.has(next)) continue;
visited.add(next);
queue.push(next);
}
}
return order;
}
const adj = new Map([
["A", ["B", "C"]],
["B", ["D"]],
["C", []],
["D", []],
]);
console.log(bfs(adj, "A")); // => [ 'A', 'B', 'C', 'D' ]function shortest(adj, start, goal) {
const dist = new Map([[start, 0]]);
const queue = [start];
let head = 0;
while (head < queue.length) {
const node = queue[head++];
if (node === goal) return dist.get(node);
for (const next of adj.get(node) ?? []) {
if (dist.has(next)) continue;
dist.set(next, dist.get(node) + 1);
queue.push(next);
}
}
return -1;
}
console.log(shortest(adj, "A", "D")); // => 2Common Gotchas
Mark visited on enqueue
otherwise a dense graph enqueues the same node repeatedly and you blow memory.
`array.shift()` is O(n)
use a `head` index for large queues.
Weighted graphs need a different algorithm
BFS distance is edge count, not weight sum.
Disconnected graphs
loop over all nodes as starts if you must visit every component.