Simulated Annealing

Simulated Annealing pathfinding algorithm — interactive grid visualization, pseudocode in five languages, and complexity reference.

Time O(steps) Unweighted Heuristic Probabilistic

Implementation

function annealingPathfind(grid, start, end, allowDiag, hFn) {
  const h = hFn || HEURISTICS.manhattan;
  const prev = new Map();
  let r = start[0];
  let c = start[1];
  let temp = 1.0;
  for (let step = 0; step < grid.length * grid[0].length * 2; step++) {
    visitNode(r, c);
    if (r === end[0] && c === end[1]) {
      reconstructPath(prev, start, end);
      return;
    }
    const neighbors = getNeighbors(grid, r, c, allowDiag);
    if (!neighbors.length) break;
    const __pattern1 = neighbors[Math.floor(Math.random() * neighbors.length)];
    const nr = __pattern1[0];
    const nc = __pattern1[1];
    const delta = h(r, c, end[0], end[1]) - h(nr, nc, end[0], end[1]);
    if (delta > 0 || Math.exp(delta / temp) > Math.random()) {
      const nk = key(nr, nc);
      if (!prev.has(nk) && !(nr === start[0] && nc === start[1])) prev.set(nk, [r, c]);
      r = nr;
      c = nc;
      pushFrontier(r, c);
    }
    temp *= 0.99;
    if (temp < 0.001) temp = 0.001;
  }
  reportNoPath();
}