Beam Search (k=4)

Beam Search (k=4) pathfinding algorithm — interactive grid visualization, pseudocode in five languages, and complexity reference.

Time O(k * depth * branching) Unweighted Heuristic Informed

Implementation

function beamPathfind(grid, start, end, allowDiag, hFn) {
  const h = hFn || HEURISTICS.manhattan;
  const beamWidth = 4;
  let beam = [{
    r: start[0],
    c: start[1]
  }];
  const visited = new Set([key(start[0], start[1])]);
  const prev = new Map();
  while (beam.length) {
    const candidates = [];
    for (const node of beam) {
      visitNode(node.r, node.c);
      if (node.r === end[0] && node.c === end[1]) {
        reconstructPath(prev, start, end);
        return;
      }
      for (const [nr, nc] of getNeighbors(grid, node.r, node.c, allowDiag)) {
        const neighborKey = key(nr, nc);
        if (visited.has(neighborKey)) continue;
        visited.add(neighborKey);
        prev.set(neighborKey, [node.r, node.c]);
        candidates.push({
          r: nr,
          c: nc,
          f: h(nr, nc, end[0], end[1])
        });
        pushFrontier(nr, nc);
      }
    }
    sortByField(candidates, "f");
    beam = candidates.slice(0, beamWidth);
  }
  reportNoPath();
}