Skip to main content
Intermediate ~16 min read

Breadth-First Search

Explore in rings, nearest first, the queue-driven traversal that finds shortest paths in unweighted graphs.

Prerequisites: Graph Representations, Queues

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. 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. 2

    Loop: dequeue, process

    Process the node (count it, record distance, check if it's the goal).

  3. 3

    Enqueue unvisited neighbors

    For each neighbor not yet visited: mark visited, set parent[v] = current, enqueue.

  4. 4

    Queue empty → done

    Everything reachable has been visited. Anything unvisited belongs to another component.

BFS with shortest path reconstruction

bfs.js
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 / caseCostNotes
Time (adjacency list)O(V + E)each vertex enqueued once, each edge scanned once
SpaceO(V)queue + visited + parent
Shortest path (unweighted)guaranteedrings expand in distance order
Grid variantO(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).

Check your understanding

  1. 1.Why does the FIFO queue produce shortest paths?
  2. 2.When should a node be marked visited?
  3. 3.BFS returns a 5-edge path from A to B. Later you learn one edge has weight 100 while all others cost 1. What now?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Visualize it

BFS & DFS Maze Explorer

Play, pause, and scrub the real algorithm step by step.

Play it

Maze Runner

Race your own path through a maze, then watch BFS find the provably shortest route, and DFS show why 'a path' …

Keep going