Depth-First Search

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

Time O(V + E) Unweighted Uniform

Implementation

function dfsPathfind(grid, start, end, allowDiag) {
  const visited = new Set([key(start[0], start[1])]);
  const prev = new Map();
  const stack = [[start[0], start[1]]];
  while (stack.length) {
    const __pattern1 = stack.pop();
    const cr = __pattern1[0];
    const cc = __pattern1[1];
    visitNode(cr, cc);
    if (cr === end[0] && cc === end[1]) {
      reconstructPath(prev, start, end);
      return;
    }
    const neighbors = getNeighbors(grid, cr, cc, allowDiag).reverse();
    for (const [nr, nc] of neighbors) {
      const neighborKey = key(nr, nc);
      if (visited.has(neighborKey)) continue;
      visited.add(neighborKey);
      prev.set(neighborKey, [cr, cc]);
      stack.push([nr, nc]);
      pushFrontier(nr, nc);
    }
  }
  reportNoPath();
}