/* Maze problem (four-way) input:16 1 1 1 0 1 1 each 0 1 0 1 0 1 1 0 0 1 1 1 1 1 1 0 0 1 0 0 1 1 0 0 1 1 0output:yes ( (2,2) (3,1) (4,1) (5,2) (5,3) (6,4) (6,5) (5,6) (4,5) (4,6) (5,7) (5,8) (In ()) (recursive) (a) (6,8) (2,2) (3,3) (3,4) (4,5) (5,7) (6,8) (Stack) */#include <iostream> #include <stack>using namespace std;struct point{int x;int y;}; int maze[10][10];stack<point> Sp;int Dir[4][2] = {{-1, 0},{0,-1}, {0, 1}, {1, 0}};void Create (int row, int Column) {//Create a maze, notice that 0 means walk, 1 means wall, the entire input maze is again walled, processing without special attention to the boundary problem int I, j;for (i = 0; I<row + 2; i++) maze[i][0] = Maze[i][c Olumn + 1] = 1;for (j = 0; J<column + 2; j + +) Maze[0][j] = Maze[row + 1][j] = 1;for (i = 1; I <= row; i++) {for (j = 1 ; J <= Column; J + +) {cin >> maze[i][j];}} /*bool mazepath (int row,int column,int x,int y) {//Determine if there is a path from the inlet to the exit, save the Path (recursive) maze[x][y] = -1;point temp;temp.x = x;temp.y = y; Sp.push (temp); for (int i=0; i<4; i++) {if (x + dir[i].x = row && y + dir[i].y = = column) return Trueif (maze[x + dir[i].x][y + dir[i].y] = = 0) {if (Mazepath (row,column,x + dir[i].x,y + dir[i].y)) return true;}} Sp.pop (); return false;} */bool Mazepath (int row, int column, int x, int y) {//pushes the starting point into the stack, then presses into the stack based on whether the starting point is up or down, and if none of the four directions are feasible, pop up the top of the stack element// The SP is used to save the path point first;stack<point>savepoint;first.x = x; First.y = Y;savepoint.push (first), while (!savepoint.empty ()) {Point curr = Savepoint.top (); Sp.push (Curr); MAZE[CURR.X][CURR.Y] = -1;bool flag = true;for (int i = 0; i < 4; i++) {int NX = curr.x + dir[i][0];int ny = curr.y + di R[i][1];if (NX = = Row && NY = = column) return true;if (maze[nx][ny] = = 0) {Point p;p.x = NX; p.y = Ny;savepoint.push (p); flag = false;}} if (flag) {Savepoint.pop (); Sp.pop ();}} return false;} void Printpath (int row, int column) {//output path from ingress to egress point temp;temp.x = ROW;TEMP.Y = Column;stack<point> Pp;pp.push ( temp); while (!sp.empty ()) {temp = Sp.top (); Sp.pop ();pp. push (temp);} while (!pp.empty ()) {temp = Pp.top (); cout << ' (' << temp.x << ', ' << temp.y << ' << ';pp. Pop ();} cout << Endl;} int main () {freopen ("Sample_input.txt", "R", stdin); int T, row, column;cin >> t;while (t--) {cin >> row >> Column Create (row, column), if (Mazepath (Row, column, 1, 1)) {cout << "YES" << Endl; Printpath (row, column);} else cout << "NO" << Endl;} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Dfs asks for maze problem