Depth-first search
Is there any route at all?
Follows one route as deep as it can before backing up. It finds a path quickly, but not necessarily a short one.
Depth-first search is breadth-first search with the queue swapped for a stack: it always continues from the newest cell. It runs down one corridor until it meets a wall or a visited cell, then backs up to the last junction and tries the next branch.
That makes it cheap and good at answering whether the goal can be reached, and it is the basis of many other algorithms: generating mazes, ordering tasks, finding connected regions. As a path finder its weakness is that the first path it finds can wander across the whole map.
Loading the demo…
The grid with depth-first search selected. On open ground the path it returns snakes around, rarely close to the shortest.
- 01Push the start on a stack and mark it visited.
- 02Pop the newest cell.
- 03If it is the goal, follow the stored parents back to the start.
- 04Otherwise push each unvisited neighbour, recording where it came from.
- 05Repeat until the stack is empty.
function dfs(start, goal):
stack = [start]
parent = {start: none}
while stack is not empty:
cell = stack.pop() # the newest cell
if cell == goal: return path_from(parent, goal)
for n in neighbours(cell):
if n not in parent:
parent[n] = cell
stack.push(n)
return no_pathThe same as breadth-first search in the worst case. On a tree, or with recursion, memory is only the depth of the current route.
- A few lines, and little memory on trees.
- Answers “is the goal reachable?” quickly.
- Building block for many other algorithms.
- The path found can be far from the shortest.
- The result depends on the order neighbours are visited.
- Ignores costs and the goal’s position.
- 01PathfindingRun it on an empty grid and compare its path length to the other four with “Compare all”.