The Tourist (Joke)

The Tourist (Joke) pathfinding algorithm — interactive grid visualization, pseudocode in five languages, and complexity reference.

Time O(steps) Unweighted Heuristic Experimental

Implementation

function touristPathfind(grid, start, end, allowDiag, hFn) {
  const h = hFn || HEURISTICS.manhattan;
  const prev = new Map();
  const visited = new Set([key(start[0], start[1])]);
  let r = start[0];
  let c = start[1];
  for (let step = 0; step < grid.length * grid[0].length * 4; 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 fresh = neighbors.filter(([nr, nc]) => !visited.has(key(nr, nc)));
    let pick;
    if (fresh.length) {
      sortByHeuristic(fresh, h, end[0], end[1]);
      pick = fresh[0];
    } else {
      pick = neighbors[Math.floor(Math.random() * neighbors.length)];
    }
    const pk = key(pick[0], pick[1]);
    visited.add(pk);
    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();
}