C language Recursive Backtracking Method for Maze solving and Recursive Backtracking for Maze solving
In this example, a 10*10 maze is randomly generated, and the solution of this maze is output below.
The solution is to enter from the coordinate () and go out from (,). The priority line is first right, bottom, top, and last left.
Many people use stack-related knowledge to solve this problem. In this example, the process of finding a line is not used in the stack, but the TRACE method is used to "erase" the lines that cannot be determined.
Let's talk about the code.
# Include <stdio. h> # include <stdlib. h> # include <time. h> // include the function static int maze [10] [10] that generates random numbers based on the current time; // create a maze int creatmaze () {srand (unsigned) time (NULL); for (int I = 0; I <10; I ++) {for (int j = 0; j <10; j ++) {if (I = 1 & j = 1) | (I = 8 & j = 8) maze [I] [j] = 0; else maze [I] [j] = rand () % 3; // to ensure a small number of walls, the random number 1 is the wall, 0 and 2 are path if (maze [I] [j] = 2) maze [I] [j] = 0; if (maze [I] [j] = 1 | I = 0 | I = 9 | j = 0 | j = 9) // The Labyrinth frame is a wall {maze [I] [j] = 1; print F ("O");} else printf ("");} printf ("\ n");} printf ("\ n ");} // output line (result) void printroute () {for (int I = 0; I <10; I ++) {for (int j = 0; j <10; j ++) {if (maze [I] [j] = 1) printf ("O"); else if (maze [I] [j] = 0) printf (""); else if (maze [I] [j] = 2) printf ("X");} printf ("\ n ");}} // find the line void findroute (int I, int j) {if (I = 8 & j = 8) // The boundary condition, that is, find the way out {printroute (); exit (0);} else {if (maze [I] [j + 1]! = 1 & maze [I] [j + 1]! = 2) // determine whether the right side of the current position is a wall (likewise) {maze [I] [j] = 2; // use 2 as the line sign j ++; findroute (I, j); // recursive j --; // trace maze [I] [j] = 0;} if (maze [I + 1] [j]! = 1 & maze [I + 1] [j]! = 2) // {maze [I] [j] = 2; I ++; findroute (I, j); I --; maze [I] [j] = 0;} if (maze [I-1] [j]! = 1 & maze [I-1] [j]! = 2) // {maze [I] [j] = 2; I --; findroute (I, j); I ++; maze [I] [j] = 0;} if (maze [I] [J-1]! = 1 & maze [I] [J-1]! = 2) // left {maze [I] [j] = 2; j --; findroute (I, j); j ++; maze [I] [j] = 0 ;} if (I = 1 & j = 1 & maze [1] [2] = 1 & maze [2] [1] = 1) // This field is used to determine whether the right and bottom of the entrance are paths. If there is a wall at both ends, no path is directly output {printf ("no way \ n "); exit (0) ;}} int main () {creatmaze (); findroute (); printf ("no way \ n"); // no way is found}
Sample output: