#include <iostream> using namespace std; #include <stack> #include <assert.h> //初始化迷宫 void InitMaze(int* maze,int row, int col) { FILE* fout = fopen("Maze.txt", "r"); assert(fout); for (int i = 0; i < row; ++i) { for (int j = 0; j < col;) { char ch = fgetc(fout); if (ch == EOF) { cout<<"Init MazeMap fail"<<endl; exit(false); } if (ch == '1' || ch == '0') { maze[i * row + j] = ch - '0'; ++j; } } } fclose(fout); } struct Pos { int _row; //行 int _col; //列 }; //打印迷宫 void PrintMaze(int* maze, int row, int col) { for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { cout<<maze[i * row + j]<<" "; } cout<<endl; } cout<<endl; } //判断当前位置是否为0 inline bool CheckIsPassWay(int* maze, int row, int col, Pos pos) { if (pos._row < row && pos._col < col && maze[pos._row * col + pos._col] == 0) { return true; } return false; } //判断迷宫是否有出口 bool GetMazePath(int* maze, int row, int col, Pos entry, stack<Pos>& path) { assert(maze); path.push(entry); maze[entry._row * col + entry._col] = 2;//将走过的路标记为2 while (!path.empty()) { Pos cur = path.top(); Pos next = cur; if (row-1 == next._row)//找到出口 { return true; } //判断右边是否为0 next = 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();//四个方向都不通,返回上一步 } return false;//栈为空,没有找到出口 } void TestMaze() { int maze[10][10] = {}; Pos entry = {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); } int main() { TestMaze(); return 0; }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。