Biased Random Walk

Biased Random Walk pathfinding algorithm — interactive grid visualization, pseudocode in five languages, and complexity reference.

Time O(steps) Unweighted Heuristic Probabilistic

Implementation

function biasedrandomwalkPathfind(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 * 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;
    sortByHeuristic(neighbors, h, end[0], end[1]);
    const pick = neighbors[Math.random() < 0.7 ? 0 : Math.floor(Math.random() * neighbors.length)];
    const pk = key(pick[0], pick[1]);
    if (!prev.has(pk) && !(pick[0] === start[0] && pick[1] === start[1])) prev.set(pk, [r, c]);
    r = pick[0];
    c = pick[1];
    pushFrontier(r, c);
  }
  reportNoPath();
}