BFS explores a graph in rings around the start: everything 1 edge away, then everything 2 edges away, and so on. The queue is the mechanism, FIFO ensures nodes discovered early are expanded early, and since every edge adds exactly one step of distance, the first time BFS reaches any node is via a shortest path. That guarantee (unweighted graphs only!) is BFS's superpower.
The algorithm is four moving parts: a queue, a visited set, the current node's neighbor loop, and, when you need the actual path, not just the distance, a parent map recording where each node was first discovered from. Walk the parent chain backward from the goal to reconstruct the route. On grids (mazes), nodes are cells and edges connect orthogonal open neighbors, BFS just works.
BFS by the numbers
- 1
Enqueue start, mark visited
Mark at ENQUEUE time, not dequeue time, otherwise the same node enters the queue twice via different paths and you do duplicate work.
- 2
Loop: dequeue, process
Process the node (count it, record distance, check if it's the goal).
- 3
Enqueue unvisited neighbors
For each neighbor not yet visited: mark visited, set parent[v] = current, enqueue.
- 4
Queue empty → done
Everything reachable has been visited. Anything unvisited belongs to another component.
BFS with shortest path reconstruction
function bfsShortestPath(adj, start, goal) {
const queue = [start];
const visited = new Set([start]); // mark when ENQUEUED
const parent = new Map();
while (queue.length) {
const node = queue.shift(); // FIFO, the shortest-path guarantee
if (node === goal) {
const path = [goal];
for (let cur = goal; parent.has(cur); cur = parent.get(cur)) {
path.unshift(parent.get(cur)); // walk parents back to start
}
return path;
}
for (const nb of adj[node]) {
if (!visited.has(nb)) {
visited.add(nb);
parent.set(nb, node);
queue.push(nb);
}
}
}
return null; // goal unreachable
}| Operation / case | Cost | Notes |
|---|---|---|
| Time (adjacency list) | O(V + E) | each vertex enqueued once, each edge scanned once |
| Space | O(V) | queue + visited + parent |
| Shortest path (unweighted) | guaranteed | rings expand in distance order |
| Grid variant | O(rows × cols) | V = cells, E = 4 per cell |
Practice
Graph: 0–1, 0–2, 1–3, 2–3, 3–4 (undirected). BFS from 0 with neighbors visited in ascending order: what is the visit ORDER, and the shortest path to 4?
Reveal explanation
Visit order: 0 → (neighbors 1, 2) → (3 via 1) → (4 via 3): 0, 1, 2, 3, 4. Shortest path to 4: parent[4]=3, parent[3]=1, parent[1]=0 → 0→1→3→4 (3 edges, BFS guarantees this is minimal).