#include <iostream> using namespace std; #define N 10 #include <stack> struct pos { int _row;// 行 int _col;// 列 }; bool cheakstep(pos a) { if(a._col > -1||a._col < N-1|| a._row > -1||a._row < N-1) { return true ; } return false ; } bool IsPath(int arr[][N],pos Nowloction,stack<pos>& s) { pos tmp = Nowloction; //入栈标记 栈不为空 s.push (Nowloction); arr[tmp._row][tmp._col] = 2; while(!s.empty ()) { //shang pos Now = s.top (); if(Now._row == N-1) { return true ; } Now._row -=1; if(cheakstep(Now)==true && arr[Now._row][Now._col]==0) { s.push (Now); arr[Now._row ][Now._col ]=2; continue; } //you Now = s.top (); Now._col +=1; if(cheakstep(Now)==true && arr[Now._row][Now._col]==0) { s.push (Now); arr[Now._row ][Now._col ]=2; continue; } //xia Now = s.top (); Now._row +=1; if(cheakstep(Now)==true && arr[Now._row][Now._col]==0) { s.push (Now); arr[Now._row ][Now._col ]=2; continue; } //zuo Now = s.top (); Now._col -=1; if(cheakstep(Now)==true && arr[Now._row][Now._col]==0) { s.push (Now); arr[Now._row ][Now._col ]=2; continue; } else { Now = s.top (); arr[Now._row ][Now._col ] = 3; s.pop (); } } return false ; } int main() { //定义一个二维数组存放迷宫 1表示墙0表示路 //定义一个栈存放路径 //定义一个入口地址 int arr[N][N]={ 1,1,}; pos entry = {2,0}; stack<pos> path; bool ret = IsPath(arr,entry,path); if(ret == true ) { cout<< "走出迷宫"<<endl; } else cout<< "没有走出迷宫"<<endl; for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { cout<<arr[i][j]; } cout<<endl; } cout<<endl; return 0; }