迷宫
2015-11-03 20:55
183 查看
#include<iostream> #include<stack> using namespace std; #pragma warning(disable:4996) const int N = 5; //从文本中读取迷宫存入数组 template<class T> void InitMaze(T** arr) { FILE* f = fopen("maze.txt", "r"); if (f == NULL) { cout << "open maze fail" << endl; return; } for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { int ch = fgetc(f); if (ch == ' ' || ch == '\n') { j -= 1; } else { arr[i][j] = ch - '0'; continue; } } } fclose(f); } struct Step //当前位置信息 { int _row; //行 int _col; //列 }; template<class T> bool Maze(T** arr, int EntranceRow, int EntranceCol) { Step step; stack<Step> s; step._row = EntranceRow; step._col = EntranceCol; if (s.empty()) { arr[EntranceRow][EntranceCol] = 2; //将走过的位置赋值为2 s.push(step); //将入口信息插入栈中 } while (step._row < N - 1) { //向上走 step._row -= 1; if (step._row >= 0 && step._row < N && step._col >= 0 && step._col < N && !s.empty()) { if (arr[step._row][step._col] == 0) { arr[step._row][step._col] = 2; s.push(step); continue; } } //向右走 step._row += 1; //恢复行数 step._col += 1; if (step._row >= 0 && step._row < N && step._col >= 0 && step._col < N && !s.empty()) { if (arr[step._row][step._col] == 0) { arr[step._row][step._col] = 2; s.push(step); continue; } } //向下走 step._col -= 1; //恢复列数 step._row += 1; if (step._row >= 0 && step._row < N && step._col >= 0 && step._col < N && !s.empty()) { if (arr[step._row][step._col] == 0) { arr[step._row][step._col] = 2; s.push(step); continue; } } //向左走 step._row -= 1; //恢复行数 step._col -= 1; if (step._row >= 0 && step._row < N && step._col >= 0 && step._col < N && !s.empty()) { if (arr[step._row][step._col] == 0) { arr[step._row][step._col] = 2; s.push(step); continue; } } if (!s.empty()) { step = s.top(); arr[step._row][step._col] = 3; //讲行不通的位置赋值为3 s.pop(); step = s.top(); //取出栈顶元素 continue; } else { return false; } } return true; } template<class T> void Print(T** arr) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << arr[i][j] << " "; } cout << endl; } cout << endl; } int main() { //动态开辟二维数组 int** arr = new int* ; for (int i = 0; i < N; i++) { arr[i] = new int ; } InitMaze<int>(arr); Maze(arr,1,0); Print<int>(arr); for (int i = 0; i < N; i++) //释放二维数组 { delete[] arr[i]; arr[i] = NULL; } delete[] arr; arr = NULL; getchar(); return 0; }
相关文章推荐
- DFS 暴力 1007
- 迷茫大三
- 让input支持 ctrl v上传粘贴图片? 让input支持QQ截图或剪切板中的图像数据(Java实现保存)
- 查看程序的启动参数,入口参数
- 观点的不同
- RelativeLayout相对布局
- 使用 jdbc 连接 mysql 数据库
- 数据库中文问题
- 决策树模型组合之随机森林与GBDT
- hdu 1254 推箱子(嵌套搜索,bfs中有dfs)
- swift 学习记录(四)
- 关于NSNotificationCenter监听并且传递数据
- linux下 mysql 忘记密码解决方案
- Codevs_P3269 混合背包
- bitmap算法
- mongo客户端mongo VUE增删改查
- C++设计模式[三]建造者模式
- 栈的压入、弹出序列
- Android Studio Gradle代理设置
- nyist 733 万圣节派对