Breadth-First Search

Breadth-First Search explores the grid in expanding rings: it visits every neighbour of the start, then every neighbour of those, and so on, using a FIFO queue. The first time it reaches the goal it has found a shortest path in terms of number of steps.

Time O(V + E) Unweighted Uniform

How it works

Breadth-First Search explores the grid in expanding rings: it visits every neighbour of the start, then every neighbour of those, and so on, using a FIFO queue. The first time it reaches the goal it has found a shortest path in terms of number of steps.

Because it expands uniformly in all directions, BFS guarantees the fewest-edges path on an unweighted grid.

Implementation

function bfsPathfind(grid, start, end, allowDiag) {
  const visited = new Set([key(start[0], start[1])]);
  const prev = new Map();
  const queue = [[start[0], start[1]]];
  while (queue.length) {
    const __pattern1 = queue.shift();
    const cr = __pattern1[0];
    const cc = __pattern1[1];
    visitNode(cr, cc);
    if (cr === end[0] && cc === end[1]) {
      reconstructPath(prev, start, end);
      return;
    }
    for (const [nr, nc] of getNeighbors(grid, cr, cc, allowDiag)) {
      const neighborKey = key(nr, nc);
      if (visited.has(neighborKey)) continue;
      visited.add(neighborKey);
      prev.set(neighborKey, [cr, cc]);
      queue.push([nr, nc]);
      pushFrontier(nr, nc);
    }
  }
  reportNoPath();
}

Advantages

  • Guarantees the shortest path on unweighted grids.
  • Simple, predictable, and complete — it always finds a path if one exists.

Disadvantages

  • Ignores edge weights, so it is not suitable for weighted terrain.
  • Explores many cells; A* is far more focused when a heuristic is available.

When to use it

Use BFS for shortest paths on uniform-cost grids, flood fills, and reachability checks.