Fringe Search

Fringe Search pathfinding algorithm — interactive grid visualization, pseudocode in five languages, and complexity reference.

Time O((V + E) log V) typical Weighted Heuristic Informed

Implementation

function fringePathfind(grid, start, end, allowDiag, hFn) {
  const h = hFn || HEURISTICS.manhattan;
  const prev = new Map();
  const bestCost = new Map([[key(start[0], start[1]), 0]]);
  const startNode = {
    r: start[0],
    c: start[1],
    g: 0
  };
  let fringe = [startNode];
  let threshold = h(start[0], start[1], end[0], end[1]);
  while (fringe.length) {
    const nextFringe = [];
    let minNext = Infinity;
    for (const node of fringe) {
      const f = node.g + h(node.r, node.c, end[0], end[1]);
      if (f > threshold) {
        if (f < minNext) minNext = f;
        continue;
      }
      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 ng = node.g + stepCost(grid, node.r, node.c, nr, nc);
        const neighborKey = key(nr, nc);
        if (!bestCost.has(neighborKey) || ng < bestCost.get(neighborKey)) {
          bestCost.set(neighborKey, ng);
          prev.set(neighborKey, [node.r, node.c]);
          nextFringe.push({
            r: nr,
            c: nc,
            g: ng
          });
          pushFrontier(nr, nc);
        }
      }
    }
    if (!nextFringe.length) {
      if (minNext === Infinity) break;
      threshold = minNext;
    }
    fringe = nextFringe;
  }
  reportNoPath();
}