Design and implementation of maze problem algorithm

Source: Internet
Author: User
Tags exit in


Maze Solver
Finding all the paths from the entrance to the exit in the maze is a classic programming problem. Because the computer solves the maze, usually uses is "the poor lift solves" the method, namely embarks from the entrance, moves forward in a certain direction to explore, if can walk, then continues to walk, otherwise along the original road returns, in another direction then continues to explore, until all possible paths have explored so far. In order to ensure that it can be returned in any position along the original path, it is clear that a last-in, first-out structure is required to hold the path from the entry to the current location.  Therefore, the application of "stack" in the algorithm of Maze path is a natural thing. Let's say the maze looks like this:

1 1 1 1 1 1 1 1
1 0 1 1 0 1 0 1
1 0 1 0 0 1 0 1
1 1 0 3 1 0 1 1
1 0 0 1 0 0 4 1
1 0 0 0 0 1 1 1
1 0 1 0 0 1 0 1
1 0 1 0 0 0 1 1
1 1 1 1 0 0 0 1
1 1 1 1 1 1 1 1


Suppose "current position" refers to "a block position in a map at a certain point in the search process", the basic idea of an algorithm for finding a path in a maze is to include the current path if the current position is "available", and continue to explore the "next position", which is to toggle "next position" to "current position", so repeat until Export; If the current position is "not available", you should follow the "to" back to the "previous channel block" and then continue exploring in a direction other than "to", if the channel block is "unreachable" for four weeks and four blocks, you should remove the channel block from the current path. The so-called "next position" refers to the "current position" four weeks in four directions (east, south, west, north) on adjacent blocks. Assuming that the stack s records "Current Path", the top of the stack is "the last channel block on the current path".      As a result, the "Include Path" operation is "current position in the stack", "remove the previous channel block from the current path" is "out of the stack." The algorithm for finding a path from the entrance to the exit in the maze can be described as follows:
Set the initial value of the current position as the entry position;

Do

If the current position is available,
The

Inserts the current position into the top of the stack;//include Path

If the position is an exit position, the end;//The path is stored in the stack

Otherwise, toggle the current position of the east adjacent square is the new current position;

Otherwise

{
If the stack is not empty and the top position of the stack is not explored,

The new current position is set to the next adjacent block of the top position of the stack that is rotated in a clockwise direction;

If the stack is not empty, but the top position of the stack is not available around,

The

Delete the top position of the stack;//delete the channel block from the path

If the stack is not empty, re-test the new stack top position,

Until a contiguous block is found or the stack is out of stack to empty;

}
}while (Stack not empty);

Source: (Common method)

#include <stdio.h> #include <stdlib.h> #define TMALLOC (type,n) (type *) malloc ((n) *sizeof (type)) #define Gpath ' # '//macros define when the maze is able to walk through the path of the graph # define Gwall '-'//macros define when the maze can walk through the non-path route Graph/* struct Tcell used to represent a lattice of information in the Maze node stored in the maze  The position information of the current node in the search for a way out, node_stack[] The data of each node in the storage stack move[] store up and down four azimuth */typedef struct cell{int row;  Store line number int col;  Store column number int dir; Holds 4 positions, 0 is right, 1 is lower, 2 is left, 3 is upper}tcell, *tcellptr;int verify_mat (const char *, int*, int*); int * * READ_MAP (const char *, int, int); void Show_map (int *, int, int), void destroy_map (int *, int), int * * SETUP_MAT (int, int); Tcellptr setup_stack (int, int), void search_maze (int * *, int * *, tcellptr, int, int), void show_route (int * *, tcellptr, I  NT, int, int);//Search Maze path function, if there is a way out, then print out the way out void Search_maze (int **maze, int **mark, tcellptr pstack, int nrow, int ncol) {int            MOVE[4][2] ={{1, 0}, {0, 1}, {-1, 0}, {0, -1}};int top = 1;          Stack top pointer of path stack int found = 0;    Mark whether to find the maze out of the way, found=1 means to find the way int orientation = 0; Orientation storing the current elementThe direction of the Traverse, 0 is right, 1 is lower, 2 is left, 3 is upper int next_row, Next_col;          Next_row, Next_col respectively holds the row and column values of the next element of the current element Tcell Curcell;      Current Maze unit//The Labyrinth Inlet unit is pressed into the top of the stack (note that a layer of "outer wall" is added to the perimeter of the maze, so the entry coordinates are () Pstack[0].row = 1;   Pstack[0].col = 1;pstack[0].dir = 0;mark[1][1] = 1; The maze entry element is marked to indicate that the unit has traversed while (top >= 0 &&!found) {//If the stack is non-empty (not returned to the inlet unit) and the maze exit is not found, the path continues to look for Curcell = pstack[    top--]; Stack top element out of stack orientation = Curcell.dir; The direction value of the top element of the stack is the current direction//starting at the current direction of the Curcell, walking clockwise through the neighbor unit while (Orientation < 4 &&!found) {//When 4 directions are not traversed,  And did not find the maze exit Next_row = Curcell.row + move[orientation][0];  Calculates the row number of the neighbor cell in the current direction Next_col = Curcell.col + move[orientation][1]; Calculates the column number of the neighbor unit in the current direction if (Next_row = = Nrow-2 && Next_col = = ncol-2) {found = 1;//if the neighbor unit is exactly the maze exit, set the found flag to 1}else if (           !maze[next_row][next_col] &&!mark[next_row][next_col]) {//If the neighbor unit is reachable and has not been accessed mark[next_row][next_col] = 1;        Mark the cell as visited Pstack[top].dir = ++orientation;                        The next direction of the current element is assigned to the current element top++; Put this element into the stackTop Pstack[top].row = Next_row;pstack[top].col = Next_col;pstack[top].dir = 0;curcell.row = Next_row;curcell.col = Next_col                        ; orientation = 0; Direction control dir Clear 0 printf ("%d%d\n", Next_row, Next_col);} elseorientation++;} while (dir < 4 &&!found)}//while (Top > 1 &&!found)//If a maze outlet is found, the map output function is called, otherwise a hint is given to tell the user that the maze has no way out if ( Found) {Show_route (Maze, Pstack, Nrow, Ncol, top);} else{printf ("\ n the maze has no way!") \ n ");}} int main () {int nrow_map = 0, Ncol_map = 0;const char *filename = "Map.txt"; int **maze;int **mark; Tcellptr pstack;if (!verify_mat (filename, &nrow_map, &ncol_map)) {printf ("Check maze Map file: File read failed, or map of elements per row is incompatible \ n") ); exit (0);} Read in map file Maze = read_map (filename, nrow_map, ncol_map);//generate Maze access tag matrix Mark = Setup_mat (Nrow_map, ncol_map);// Initialize the path probe stack pstack = Setup_stack (Nrow_map, Ncol_map); Search_maze (Maze, Mark, Pstack, Nrow_map, ncol_map);// Destroys dynamically allocated memory Destroy_map (maze, nrow_map) for storing maze maps,//destroys memory dynamically allocated for storing maze access tokens Destroy_map (mark, nrow_map);//Destroy Path probe stack free ( Pstack); system ("Pause"); return 0;} Check the maze map//function function: Read the matrix information from the file, verify that the number of elements in each row is the same, if it is returned 1, if it returns the 0//function return value: The file read successfully returned 1, and the use of pointers to modify the value of the incoming two integer parameter is the number of rows and columns int verify_ Mat (const char *filename, int* pnrow_map, int* pncol_map) {int nrow_map = 0, Ncol_map = 0, counter = 0;char temp; File *fp;fp=fopen (filename, "R"); if (FP) {//If unable to open the file, prompt the user for the maze file is not ready and exit the program printf ("The file ' Map.txt ' was opened successful ly for Read.\n ");} else{printf ("The file ' Map.txt ' can not is opened!\n"); exit (0);} The line number of the maze matrix is stored in the NROW_MAP, the column number is stored in the Ncol_map, and the number of rows and columns of the maze matrix is checked for equality while (1) {temp = fgetc (FP); if (temp = = EOF) {//file is read out, loop if ( Counter! = Ncol_map) {//If the column number of the maze matrix is not all the same, display the prompt and exit the program printf ("\ n the number of elements in any column of the maze matrix must be the same, modify the maze in the map.txt and then run the program!") "); return 0;} Else{nrow_map++;break;}} if (temp! = ' \ n ') {counter++;} else{//Read in line break if (counter = = ncol_map) counter = 0;else {if (Ncol_map = = 0) {ncol_map = Counter;counter = 0;} else{//If the line number of the maze matrix is not all the same, display the prompt, and exit the program printf ("\ n the number of elements on any line of the maze matrix must be the same, modify the maze in the map.txt and then run the program!") "); return 0;}} nrow_map++;}} while (1) *pnrow_map = Nrow_map;*pncol_map = Ncol_Map;fclose (FP); return 1; Indicates a validation success}//create a maze map from file filename two-dimensional array int * * READ_MAP (const char *filename, int row, int column) {int **maze, I;char temp;fil E *fp;fp=fopen (filename, "R"); if (FP) {//If unable to open the file, prompt the user for the maze file is not ready and exit the program printf ("The file ' Map.txt ' was opened successfully f or read.\n ");} else{printf ("The file ' Map.txt ' can not is opened!\n"); exit (0);} Request storage space for the maze map maze = tmalloc (int *, row), if (!maze) {printf ("Request memory failed for read-in maze map \ n"); exit (0); for (i=0;i<row;i++) {Maze[i] = tmalloc (int, column), if (!maze[i]) {printf ("Request memory failed for read-in maze map \ n"); exit (0);}  for (int i = 0, i < row; i++) {for (int j = 0; j < column; J + +) {temp = fgetc (FP)-48; Convert the Assic code in the maze to the number if (temp! = 0 && Temp! = 1) {The contents of the "\ n" file can only be 0 or 1, please review and modify! "); exit (0);} else{//The value in the map file is not error, deposit it into array maze[][] maze[i][j] = temp;}       MARK[I][J] = 0; The traversal of each element in the file is marked 0//node_stack[j + i * row].dir = 0; Clear the direction elements of the stack 0}fgetc (FP);}  Fclose (FP); System ("CLS"); Clear the screen printf ("\ n This is a%d row%d column of the Maze Matrix!) \ n ", row, column); Show_map (Maze, row, column); return mAze;} Destroys the dynamically allocated memory void Destroy_map (int **my_array, int nrow) {int i;for (i=0; i<nrow; i++) Free (my_array[i]) for storing maze maps, and free (my _array);} Displays the read-in Maze data information void show_map (int * * My_array, int row, int column) {int i, j;for (i=0; i<row; i++) {for (j=0; j<column; J + +) {//my_array[i][j]=i;printf ("%2d", My_array[i][j]);} printf ("\ n");}} Dynamically generate a two-dimensional array based on the number of rows and columns entered, and populate the full 0 int * * SETUP_MAT (int row, int column) {int **matrix, i;//to request storage space for a two-dimensional array matrix = tmalloc (int *, RO W); if (!matrix) {printf ("Request memory for a two-dimensional array failed \ n"); exit (0);} for (i=0; i<row; i++) {Matrix[i] = tmalloc (int, column), if (!matrix[i]) {printf ("Request memory for two-dimensional array failed \ n"); exit (0);}}  for (int i = 0, i < row; i++) {for (int j = 0; j < column; J + +) {Matrix[i][j] = 0; The traversal of each element in a two-dimensional array is marked clear 0}}return matrix;} Tcellptr setup_stack (int nrow, int ncol) {tcellptr ps;ps = Tmalloc (Tcell, Nrow*ncol), if (!ps) {printf ("Request memory for Stack failed \ n"); exit (0);} return PS;} void Show_route (int **maze, tcellptr pstack, int nrow, int ncol, int top) {int I, j;int choice = 1;//for saving output option int * * NEWM AP = Setup_maT (Nrow, Ncol);  Newmap[][] Maze Unit for (i = 0; i < nrow; i++) for (j = 0; J < Ncol; J + +) newmap[i][j] = Gwall; Use the character "#" to populate the entire maze while (choice) {printf ("\ n" select display: \ n 1. Show the original maze map \ n 2. Show maze out of path coordinates \ n 3. Show maze exit simulator \ 0. end game \ n ");p rintf (" \ n Please select the corresponding number: "); scanf ("%d ", &choice); GetChar (); switch (choice) {//Select display mode case 0:break;case 1:show_map (Maze, Nrow,     Ncol); break;case 2:{printf ("\ nthe maze path is:"); Output exit path printf ("\ n rows \ t"), for (i = 0; I <= top; i++) printf ("\n%d\t%d", Pstack[i].row, Pstack[i].col);p rintf ("\n%d\t%d ", Nrow, ncol);//choice = 0;break;} Case 3:{//uses the symbol "-" to fill the maze unit corresponding to the path for (i = 0; I <= top; i++) {Newmap[pstack[i].row][pstack[i].col] = Gpath;} NEWMAP[NROW-2][NCOL-2] = Gpath; Fill out the exit Unit printf ("\ nthe maze of the way out of the analog display graph below \ \");//output Maze Traversal route map for (i = 0; i < Nrow; i++) {for (j = 0; J < Ncol; J + +) {printf ("%c" , Newmap[i][j]);} printf ("\ n");} break;} default:{printf ("Input error, please re-enter!") \ n "); scanf ("%d ", &choice);}} Switch (choice)}//while (choice) destroy_map (Newmap, nrow); Reclaim the allocated memory space for the Maze map}If the structure is used to represent the maze,//typedef struct//{//int * * MAZE;//Maze map (two-dimensional array)//int nrow;    Maze row number//int Ncol; Maze column number//}tmap;

The backtracking method solves the problem:

#include <iostream> #include <iomanip> #include <stdlib.h>using namespace std; #define MaxSize 100int Mg[10][10] = {//define a maze, 0 for channel, 1 for wall {1,1,1,1,1,1,1,1,1,1},{1,0,0,1,1,0,0,1,0,1},{1,0,0,1,0,0,0, 1,0,1},{1,0,0,0,0,1,1,0,0,1},{1,0,1,1,1,0,0,0,0,1},{1,0,0,0,1,0,0,0,0,1},{1,0,1,0,0,0,1,0,0,1},{               1,0,1,1,1,0,1,1,0,1},{1,1,0,0,0,0,0,0,0,1},{1,1,1,1,1,1,1,1,1,1}};struct St//define a stack, save path {int i;               The line number of the current block Int J;              The column number of the current square is int di;           DI is the bearing number of the next accessible position} St[maxsize];            define stack int top =-1;                                             Initialize stack pointer void Mgpath (int xi, int yi, int xe, int ye)//path from (Xi,yi) to (xe,ye) {int I, J, Di, find, k;top++; Initial block into Stack st[top].i = XI; ST[TOP].J = Yi; St[top].di = -1;mg[xi][yi] = -1;while (top>-1)//stack is not empty when looping {i = St[top].i;j = St[top]. J;di = st[top].di;if (i==xe && J==ye)//found exit, Output path {cout << "maze path as follows:/n "; for (k=0; k<=top; k++) {cout <<"/t ("<< st[k].i <<", "<< st[k].j <<") "; if (k+1)%5==            0) cout << Endl; Each output five blocks after a line}cout << Endl;return;}  Find = 0;while (di<4 && find==0)//Find Next removable square {di++;switch (di) {Case 0:i = st[top].i-1; j = ST[TOP].J; Break;case 1:i = st[top].i; j = st[top].j+1; Break;case 2:i = st[top].i+1; j = ST[TOP].J; Break;case 3:i = st[top].i; j = st[top].j-1; break;}                      if (mg[i][j]==0) find = 1;                               Find the path}if (find==1)//Find the next removable block {st[top].di = di;                                         Modifies the DI value top++ of the top element of the original stack; Next can walk block into the stack st[top].i = i; ST[TOP].J = j;                                 St[top].di = -1;mg[i][j] =-1;                  Avoid repeating to this block}else//There is no way to go, then the stack {MG[ST[TOP].I][ST[TOP].J] = 0; Let the location become another path can walk block top--;}} cout << "No way to go!" /n ";} int main () {Mgpath (1,1,8,8);} 


Design and implementation of maze problem algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.