#include<iostream>usingnamespacestd;#include<stack>#include<assert.h>//初始化迷宫voidInitMaze(int*maze,introw,intcol){FILE*fout=fopen("Maze.txt","r");assert(fout);for(inti=0;i<row;++i){for(intj=0;j<col;){charch=fgetc(fout);if(ch==EOF){cout<<"InitMazeMapfail"<<endl;exit(false);}if(ch=='1'||ch=='0'){maze[i*row+j]=ch-'0';++j;}}}fclose(fout);}structPos{int_row;//行int_col;//列};//打印迷宫voidPrintMaze(int*maze,introw,intcol){for(inti=0;i<row;++i){for(intj=0;j<col;++j){cout<<maze[i*row+j]<<"";}cout<<endl;}cout<<endl;}//判断当前位置是否为0inlineboolCheckIsPassWay(int*maze,introw,intcol,Pospos){if(pos._row<row&&pos._col<col&&maze[pos._row*col+pos._col]==0){returntrue;}returnfalse;}//判断迷宫是否有出口boolGetMazePath(int*maze,introw,intcol,Posentry,stack<Pos>&path){assert(maze);path.push(entry);maze[entry._row*col+entry._col]=2;//将走过的路标记为2while(!path.empty()){Poscur=path.top();Posnext=cur;if(row-1==next._row)//找到出口{returntrue;}//判断右边是否为0next=cur;next._col++;if(CheckIsPassWay(maze,row,col,next)){maze[next._row*row+next._col]=2;path.push(next);continue;}//上next=cur;next._row--;if(CheckIsPassWay(maze,row,col,next)){maze[next._row*row+next._col]=2;path.push(next);continue;}//下next=cur;next._row++;if(CheckIsPassWay(maze,row,col,next)){maze[next._row*row+next._col]=2;path.push(next);continue;}//左next=cur;next._col--;if(CheckIsPassWay(maze,row,col,next)){maze[next._row*row+next._col]=2;path.push(next);continue;}path.pop();//四个方向都不通,返回上一步}returnfalse;//栈为空,没有找到出口}voidTestMaze(){intmaze[10][10]={};Posentry={1,0};stack<Pos>path;//将走过的路径保存在栈path中InitMaze((int*)maze,10,10);PrintMaze((int*)maze,10,10);GetMazePath((int*)maze,10,10,entry,path);PrintMaze((int*)maze,10,10);}intmain(){TestMaze();return0;}