When confronted with a maze and there is the possibility of leaving markings in some way, the Trémaux algorithm is suitable.
The underlying process is essentially easy to understand using the following rules:
- Double markings are considered a blockage.
- Should only forwards and backwards be available as directions, take a step forwards.
- If you come to a crossroads, you must clearly mark the spaces on the right and left provided they have fewer than two markings. You then execute on each of the following points that match the circumstances.
- Are there no markings on the left or right: Follow a random path and mark it.
- Has the field behind the junction been marked once: Mark the previous field to identify it as a dead end.
- Are there markings on the left and/or right: Move in the direction with the fewest markings (< 2) and mark these as usual.
As long as the maze is static and solvable, this will find the way out.
If your interested in seeing it in action, I wrote a small program which demonstrates it visually right here: https://github.com/LazarusPit/maze-solver
By the way: The algorithm can be scaled to mazes with more than 4 directions per field. Only the concept of left and right might seem confusing, as there could be more than one direction per cardinal direction. In this case, you would only have to focus on all possible directions except the one you came from.