Stochastic Search

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

Time O(V + E) Unweighted Probabilistic

Implementation

function stochasticsearchPathfind(grid, start, end, allowDiag) {
  const visited = new Set([key(start[0], start[1])]);
  const prev = new Map();
  const frontier = [[start[0], start[1]]];
  while (frontier.length) {
    const idx = Math.floor(Math.random() * frontier.length);
    const __pattern1 = frontier.splice(idx, 1)[0];
    const cr = __pattern1[0];
    const cc = __pattern1[1];
    visitNode(cr, cc);
    if (cr === end[0] && cc === end[1]) {
      reconstructPath(prev, start, end);
      return;
    }
    for (const [nr, nc] of getNeighbors(grid, cr, cc, allowDiag)) {
      const neighborKey = key(nr, nc);
      if (visited.has(neighborKey)) continue;
      visited.add(neighborKey);
      prev.set(neighborKey, [cr, cc]);
      frontier.push([nr, nc]);
      pushFrontier(nr, nc);
    }
  }
  reportNoPath();
}