function dfs(grid: Grid, start: Cell, goal: Cell) {const stack: Cell[] = [start];
const seen = new Set([start]), parent = new Map();
while (stack.length > 0) {const current = stack.pop()!; // newest first
if (current === goal) return rebuild(parent, current);
for (const neighbor of neighbors(grid, current)) {if (seen.has(neighbor)) continue;
seen.add(neighbor);
parent.set(neighbor, current);
stack.push(neighbor);
}
}
return null;
}
Start at (12, 1), goal at (5, 42). The open set holds only the start.
Understanding Depth-first search
The idea
Depth-first search takes the newest open cell instead of the oldest: a stack instead of a queue. It dives down one corridor as far as it can, and only when it is stuck does it back up to the last junction with an untried neighbour.
That gives it a long, winding frontier and a path that follows the order neighbours were pushed, not the geometry of the maze. It finds a path if one exists, with tiny memory, but the path is usually far from the shortest.
The four stages
Complexity
Versus its siblings
Pseudocode
DFS(start, goal)
stack ← [start]; seen ← {start}while stack not empty
current ← pop the newest
if current = goal: return path via parent
for each neighbour of current not in seen
add neighbour to seen; parent[neighbour] ← current; push neighbour
When to use
Pitfalls
History
Depth-first search is the maze-walking method Charles Pierre Trémaux described in the 19th century: mark each passage as you enter it and back out of dead ends. John Hopcroft and Robert Tarjan turned it into a linear-time tool for graphs in 1973, and Tarjan's version won them the Turing Award in 1986.