您好,登錄后才能下訂單哦!
#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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。