Try something (move around but don't return to anywhere you've visited).
If you reach a dead end, go back a bit and reconsider which way to go at a recent intersection.
An algorithm that formalizes this is recursion with backtracking.
We make a function that takes:
The maze
The path so far
Its goal is to add one more step to the path, never backtracking, and call itself to finish the rest of the path.
But if it hits a dead end, it needs to notice that and backtrack.
Backtracking
Backtracking is implemented through the return value of a recursive call.
Recursive call may return:
A solution, or
None, indicating that only dead ends were found.
Algorithm depth_first_maze_solution:
Input: a maze and a path under consideration (partial progress toward solution). Initially, the path is just the starting point.
If the path is a solution, just return it.
Otherwise, enumerate possible next steps (not returning to a location already in the path).
For each of the possible next steps:
Add it to the path under consideration.
Make a recursive call to attempt to complete this path to a solution.
If recursive call returns a solution, return it immediately.
Otherwise, remove the last step from the path and go to the next iteration.
If we get to this point, every continuation of the path is a dead end. Return None.
Depth first
This method is also called a depth first search for a path through the maze.
Here, depth first means that we always add a new step to the path before considering any other changes (e.g. going back and modifying an earlier step).