Iterative Deepening DFS

Iterative Deepening DFS pathfinding algorithm — interactive grid visualization, pseudocode in five languages, and complexity reference.

Time O(V + E) per depth iteration Unweighted Uniform

Implementation

function iddfsPathfind(grid, start, end, allowDiag) {
  const maxDepth = grid.length * grid[0].length;
  for (let limit = 0; limit <= maxDepth; limit++) {
    const pathVisited = new Set();
    const prev = new Map();
    const found = dls(start[0], start[1], 0, limit, pathVisited, prev);
    if (found) return;
  }
  reportNoPath();
  function dls(r, c, depth, limit, pathVisited, prev) {
    const cellKey = key(r, c);
    if (pathVisited.has(cellKey) || grid[r][c] === WALL) return false;
    pathVisited.add(cellKey);
    visitNode(r, c);
    if (r === end[0] && c === end[1]) {
      reconstructPath(prev, start, end);
      return true;
    }
    if (depth === limit) {
      pathVisited.delete(cellKey);
      return false;
    }
    for (const [nr, nc] of getNeighbors(grid, r, c, allowDiag)) {
      const neighborKey = key(nr, nc);
      if (pathVisited.has(neighborKey)) continue;
      prev.set(neighborKey, [r, c]);
      const found = dls(nr, nc, depth + 1, limit, pathVisited, prev);
      if (found) return true;
      prev.delete(neighborKey);
    }
    pathVisited.delete(cellKey);
    return false;
  }
}