Hill Climbing

Hill Climbing pathfinding algorithm — interactive grid visualization, pseudocode in five languages, and complexity reference.

Time O(steps) Unweighted Heuristic Probabilistic

Implementation

function hillclimbingPathfind(grid, start, end, allowDiag, hFn) {
  const h = hFn || HEURISTICS.manhattan;
  const prev = new Map();
  let r = start[0];
  let c = start[1];
  for (let step = 0; step < grid.length * grid[0].length; step++) {
    visitNode(r, c);
    if (r === end[0] && c === end[1]) {
      reconstructPath(prev, start, end);
      return;
    }
    const neighbors = getNeighbors(grid, r, c, allowDiag);
    let best = [r, c];
    let bestH = h(r, c, end[0], end[1]);
    for (const [nr, nc] of neighbors) {
      const hv = h(nr, nc, end[0], end[1]);
      if (hv < bestH) {
        bestH = hv;
        best = [nr, nc];
      }
    }
    if (best[0] === r && best[1] === c) break;
    prev.set(key(best[0], best[1]), [r, c]);
    r = best[0];
    c = best[1];
    pushFrontier(r, c);
  }
  reportNoPath();
}