本文实例为大家分享了c++利用循环和栈实现走迷宫的具体代码,供大家参考,具体内容如下
<>强要求:强>
1,将地图的数组保存在文件中,从文件中读取行列数
2。,动态开辟空间保存地图
3,运行结束后再地图上标出具体的走法
<强>说明:强>
1,文件中第一行分别放置的是地图的行数和列数
2,其中1表示墙,即路不通,0表示路,即通路
3,程序运行结束后用2标记走过的路径
4,当走到“死胡同”时用3标记此路为死路
5,每到一个点,按照左上右下的顺序去试探
6,没有处理入口就是“死胡同”的极端情况
地图文件截图:
代码示例:maze.h
的ifndef _MAZE_H_ #定义_MAZE_H_ # include & lt; stack> # include & lt; fstream>//ifstream # include & lt; iostream> # include & lt; string> 使用名称空间性病;//坐标类 类的座位 { 公众: 座位(int值,int _y吗) :x(值) y (_y吗) {} int x; int y; };//迷宫类 类迷宫 { 私人: int * * _map;//指向地图的指针 int _row;//存放地图的行数 int _col;//存放地图的列数 公众://构造函数读取文件里的地图和行数 迷宫(const string&filePath); 私人://判断是否是路 bool IsPass (Seat&入口); 公众://开始走 bool PassMaze (stack和年代,Seat&入口);//打印地图 空白PrintMap ();//析构释放空间 ~迷宫(); }; # endif >之前 maze.cpp
//迷宫之递归实现 # include“maze.h”//构造函数 迷宫::迷宫(const string&filePath) { ifstream mapFile (filePath ofstream::); 断言(mapFile);//断言文件是否存在 字符串str_row_col;//第一行获取行和列 字符串str_temp;//临时字符串//获取行列的个数 getline (mapFile str_row_col);//读取第一行 str_temp=str_row_col。substr (0, str_row_col.find_first_of(" ");//取得字符串中的字串获取行数 _row=atoi (str_temp.c_str ());//atoi将字符串转为数字 str_temp=str_row_col.substr (str_row_col.find_first_of (', ') + 1);//取得字符串中的列数 _col=atoi (str_temp.c_str ());//atoi将字符串转为数字//分配空间 _map=new int * (_row); for (int idx=0;idx & lt;_col;+ + idx) { _map [idx]=new int [_col]; }//填充地图 int index_row=0;//放置地图二维数组的行索引 int index_col=0;//放置地图二维数组的列索引 而(! mapFile.eof ()) { getline (mapFile str_temp); char * a_line=(char *) str_temp.c_str ();//遍历一行 而(* a_line !=' \ 0 ') { 如果(* a_line==' 0 ' | | * a_line==' 1 ') { _map [index_row] [index_col + +]=* a_line——“0”;//减0是将字符‘0’的ASCII对应的十进制值减去 } a_line + +;//向后移动指针 } + + index_row; index_col=0;//每处理完一行后将列索引置0 } mapFile.close (); }//判断是否是路 bool迷宫:IsPass (Seat&条目) { 如果条目。x & lt;0 | |条目。y & lt;0 | |条目。y祝辞=_col | |条目。x祝辞=_row) { 返回true; } 如果(_map [entry.x][条目。y]==0) { 返回true; } 返回错误; }//开始走 无效的迷宫:PassMaze (Seat&条目) { stack年代; 如果(IsPass(条目)) { s.push(入口);//压栈当前位置 而(! s.empty())//栈不为空继续 { 座位curSeat=s.top ();//取得栈顶存储的位置//走到边界 如果(curSeat。x & lt;0 | | curSeat。y & lt;0 | |条目。y祝辞=_col | |条目。x祝辞=_row) { 返回; } _map [curSeat.x] [curSeat。y]=2;//将走过的路标记为2//往左走 座位了(curSeat。x, curSeat.y-1); 如果(IsPass(左)) { s.push(左); 继续; }//往上走 (curSeat座位。x - 1, curSeat.y); 如果(IsPass ()) { s.push(了); 继续; }//往右走 正确的(curSeat座位。x, curSeat.y + 1); 如果(IsPass(右)) { s.push(右); 继续; }//往下走 (curSeat坐下来。x + 1, curSeat.y); 如果(IsPass(下)) { s.push(下); 继续; }//运行到此处说明每个方向都没有路可走是死路标记为3 _map [curSeat.x] [curSeat。y]=3;//出栈这个“死路位置” s.pop (); } } }//打印地图 无效的迷宫:PrintMap () { for (int index_row=0;index_row & lt;_row;+ + index_row) { for (int index_col=0;index_col & lt;_col;+ + index_col) { cout & lt; & lt;_map [index_row] [index_col] & lt; & lt;“”; } cout & lt; & lt; endl; } cout & lt; & lt; endl; }//析构 迷宫::~迷宫() { for (int idx=0;idx & lt;_row;+ + idx) { 删除[]_map [idx]; } 删除[]_map; _map=零; } test.cpp 普通的副本(cpp)视图 int main () { 迷宫m1 (“map.txt”);//构造一个迷宫对象 m1.PrintMap ();//走之前打印 m1。4)PassMaze(座位(9日);//开始走传递迷宫入口点 m1.PrintMap ();//结束后再次打印 返回0; } c++利用循环和栈实现走迷宫