Rat in a maze
Let’s continue our adventure with examples by solving the rat in a maze problem with a back-tracking algorithm. The diagram is shown as follows:
Figure 9.6 – Illustration of the rat in a maze example
Let’s imagine that a rat is located in the top-left field on the board, which is marked as (0, 0) in the preceding figure, and we need to find a path to the exit, which is located in the bottom-right field and is marked as (7, 7). Of course, some blocks are disabled (shown in gray) and the rat cannot go through them. To reach the target, the rat can go up, down, left, or right only using the available blocks.
You can solve this problem using the recursion to check possible paths leading the rat from the entry to the exit. If the currently calculated path does not reach the exit, you backtrack and try other variants.
The main part of the implementation is the Go
method, as follows:
bool Go(int row, int col) { ...