Codele / Algorithms
Depth-first search
In a maze you walk down one path as far as it goes. At a dead end you back up to the last choice and try the next path. Depth-first search explores a map like that.
- To push is to add on top of a stack; to pop is to take the top one off. Depth-first search (DFS) goes as deep as it can down one path, then backs up and tries the next.
- It uses a stack: the last town pushed on is the first one taken off, so the search keeps going deeper.
- A town can be on the stack twice. When we take a town we already visited, we skip it.
- Recursion does the same job: each call is a step deeper, and returning from a call is backing up. The computer’s own stack of calls replaces ours.
- DFS and BFS visit the same towns, in a different order. DFS suits “is there any way through?”, BFS suits “fewest steps”.
Loading the playable lesson…