初级版迷宫问题(栈的应用)
/*(一)初级迷宫问题:0:代表通1:代表不通求迷宫的通路(二)步骤:1.创建迷宫*从文件中读取迷宫*开辟二维数组存放迷宫2.寻找通路*检查某位置是否为通*出口位置判断*走过的路用2标记*利用栈回溯(三)问题1.解决回溯中重复探测:递归2.最优解:迷宫的最短通路*/#include<iostream>#include<stdlib.h>#include<assert.h>#include<stack>#define_CRT_SECURE_NO_WARNINGS1#defineN10usingnamespacestd;structPos{size_t_row;//行size_t_col;//列};voidGetMap(int*m,intn){inti=0;intj=0;assert(m);FILE*fin=fopen("C:\\学习\\code\\数据结构\\MazeMap\\MazeMap.txt","r");assert(fin);for(i=0;i<n;i++){for(j=0;j<n;){charch=fgetc(fin);if(ch=='0'||ch=='1'){m[i*n+j]=ch-'0';j++;}}}}voidPrintMap(int*m,intn){assert(m);inti=0;intj=0;for(i=0;i<n;i++){for(j=0;j<n;j++){cout<<m[i*n+j]<<'';}cout<<endl;}}boolCheckIsAccess(int*m,intn,constPos&next){if(next._row>=0&&next._row<n&&next._col>=0&&next._col<n&&m[next._row*n+next._col]==0){returntrue;}else{returnfalse;}}boolSearchMazePath(int*m,intn,Posenrty,stack<Pos>paths){assert(m);paths.push(enrty);while(!paths.empty()){Poscur=paths.top();m[cur._row*n+cur._col]=2;//检查是否找到出口if(cur._row==n-1){returntrue;}Posnext=cur;//上next._row--;if(CheckIsAccess(m,n,next)){paths.push(next);continue;}next=cur;//右next._col++;if(CheckIsAccess(m,n,next)){paths.push(next);continue;}next=cur;//next归位//下next._row++;if(CheckIsAccess(m,n,next)){paths.push(next);continue;}next=cur;//左next._col--;if(CheckIsAccess(m,n,next)){paths.push(next);continue;}paths.pop();}returnfalse;}intmain(){intmap[N][N]={0};GetMap((int*)map,N);PrintMap((int*)map,N);Posenrty={2,0};stack<Pos>paths;cout<<endl;cout<<SearchMazePath((int*)map,N,enrty,paths);cout<<endl;PrintMap((int*)map,N);system("pause");return0;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。