IDA* Search

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

Time O(branch^depth) worst case Weighted Heuristic Informed

Implementation

function idastarPathfind(grid, start, end, allowDiag, hFn) {
  const h = hFn || HEURISTICS.manhattan;
  let threshold = h(start[0], start[1], end[0], end[1]);
  while (true) {
    const visited = new Set();
    const prev = new Map();
    const res = search(start[0], start[1], 0, threshold, visited, prev);
    if (res === true) return;
    if (res === Infinity) break;
    threshold = res;
  }
  reportNoPath();
  function search(r, c, g, bound, visited, prev) {
    const f = g + h(r, c, end[0], end[1]);
    if (f > bound) return f;
    const cellKey = key(r, c);
    if (visited.has(cellKey)) return Infinity;
    visited.add(cellKey);
    visitNode(r, c);
    if (r === end[0] && c === end[1]) {
      reconstructPath(prev, start, end);
      return true;
    }
    let min = Infinity;
    for (const [nr, nc] of getNeighbors(grid, r, c, allowDiag)) {
      const neighborKey = key(nr, nc);
      if (visited.has(neighborKey)) continue;
      prev.set(neighborKey, [r, c]);
      pushFrontier(nr, nc);
      const cost = g + stepCost(grid, r, c, nr, nc);
      const result = search(nr, nc, cost, bound, visited, prev);
      if (result === true) return true;
      if (result < min) min = result;
    }
    visited.delete(cellKey);
    return min;
  }
}