How does DFS correspond to exploring a maze?
Junctions, corners and dead ends are the vertices, and the corridors between them are the edges. The explorer marks every junction and every corridor they have walked, takes an unmarked corridor whenever there is one, and otherwise walks back the way they came. The record of the way back to the entrance is exactly what the recursion keeps on the call stack.
* The green route is still on the stack; every purple branch was a dead end, walked into and back out of. *
The correspondence, piece by piece:
| Maze | DFS |
|---|---|
| junction, corner, dead end | vertex |
| corridor | edge |
| mark on a junction | vertex label VISITED |
| mark on a corridor | edge label |
| corridor to an unmarked junction | discovery edge: recursive call |
| corridor to a marked junction | back edge: turn round |
| walking back to the previous junction | the recursive call returning |
This is an old strategy: in the 19th century Charles Pierre Trémaux described a way out of any maze by marking passages, and the method is essentially depth-first search. It walks every corridor at most twice, once in each direction, and finds the exit whenever there is one, but, like DFS, not necessarily by the shortest route.
Go deeper:
Maze-solving algorithm: Trémaux's algorithm — the marking rules, and why the method amounts to depth-first search.
Computerphile: maze solving — search algorithms put into practice on maze images, with the code to try.