C++实现迷宫问题
新建一个.txt文档来存储迷宫,输入n*n的迷宫矩阵并保存起来,如下图
//Stack.h
#pragmaoncetemplate<classT>classstack{public:stack()//构造函数:_arr(NULL),_top(0),_capacity(0){}~stack()//析构函数{if(_arr){delete[]_arr;}}public:voidPush(constT&x)//插入{_CheckCapacity();_arr[_top++]=x;}voidPop()//删除{assert(_top>0);--_top;}size_tSize()//大小{return_top;}boolEmpty()//判断栈是否为空{//return_top==0;if(_top<=0){returntrue;}elsereturnfalse;}T&Top()//获取栈顶元素{return_arr[_top-1];}protected:void_CheckCapacity(){if(_arr==NULL){_capacity=5;_arr=newT[_capacity];return;}elseif(_top==_capacity){_capacity*=2;T*tmp=newT[_capacity];for(size_ti=0;i<_top;++i){tmp[i]=_arr[i];}delete[]_arr;_arr=tmp;}}protected:T*_arr;size_t_top;size_t_capacity;};
//Maze.cpp
#define_CRT_SECURE_NO_WARNINGS1#include<iostream>usingnamespacestd;#include<assert.h>#include"Stack.h"structPos{int_row;int_col;};//函数声明voidGetMaze(int*a,intn);boolSearchMazePath(int*a,intn,Posentrance,stack<Pos>&paths);boolCheckIsAccess(int*a,intn,constPos&next);voidGetMaze(int*a,intn)//将迷宫存到一个一维数组a里{assert(a);FILE*fout=fopen("E:\\MazeMap.txt","r");//以读的方式读取迷宫矩阵assert(fout);for(inti=0;i<n;++i){for(intj=0;j<n;){charch=fgetc(fout);if(ch=='1'||ch=='0')//矩阵中‘0’为通路{a[i*n+j]=ch-'0';cout<<a[i*n+j]<<"";++j;}}cout<<endl;}cout<<endl;}boolCheckIsAccess(int*a,intn,constPos&next){introw=next._row;intcol=next._col;if(row>=0&&row<n&&col>=0&&col<n&&a[row*n+col]==0){returntrue;}else{returnfalse;}}//寻找通路,并用栈来存储boolSearchMazePath(int*a,intn,Posentrance,stack<Pos>&paths){assert(a);paths.Push(entrance);boolisfirst=true;while(!paths.Empty()){Poscur=paths.Top();a[cur._row*n+cur._col]=7;//将通路标记为7if(isfirst==false||cur._row==n-1||cur._col==n-1||cur._row==0||cur._row==0)//如果找到矩阵的四个边就表示找到通路{returntrue;}Posnext=cur;//判断当前元素的上路是否为通路,即是否为‘0’next._row--;if(CheckIsAccess(a,n,next)){paths.Push(next);continue;}//判断当前元素的下路是否为通路next=cur;next._row++;if(CheckIsAccess(a,n,next)){paths.Push(next);continue;}//判断当前元素的左路是否为通路next=cur;next._col--;if(CheckIsAccess(a,n,next)){paths.Push(next);continue;}//判断当前元素的右路是否为通路next=cur;next._col++;if(CheckIsAccess(a,n,next)){paths.Push(next);continue;}paths.Pop();isfirst=false;}returnfalse;}//打印迷宫矩阵voidPrintMaze(int*a,intn){for(inti=0;i<n;++i){for(intj=0;j<n;++j){cout<<a[i*n+j]<<"";}cout<<endl;}cout<<endl;}intmain(){intsize=5;intmazemap[25]={0};Posentrance;entrance._row=1;entrance._col=0;stack<Pos>path;GetMaze(mazemap,size);if(SearchMazePath(mazemap,size,entrance,path)){PrintMaze(mazemap,size);}system("pause");return0;}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。