数据结构迷宫问题
2016-07-28 09:37
627 查看
#include<iostream> #include<stack> using namespace std; #define N 10 struct Pos { size_t _row; size_t _col; }; void InitMaze(int maze[] )//初始化 { FILE* fOut = fopen("MazeMap.txt", "r"); if (fOut == NULL) { cout << "Open MazeMap.txt fail!" << endl; exit(-1); } for (int i = 0; i < N; ++i) { for (int j = 0; j < N;) { //int temp; //cin >> temp; char ch = fgetc(fOut); if (ch == EOF) { cout << "MazeMap Error!" << endl; exit(-1); } if (ch == '1' || ch == '0') { maze[i][j] = ch - '0'; ++j; } } } fclose(fOut); } void PrintMaze(int maze[] ) { for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { cout << maze[i][j] << " "; } cout << endl; } cout << endl; } //int** f(int N)//创建二维数组 //{ // int** array = new int* ; // for (int i = 0; i < N; ++i) // { // array[i] = new int ; // } // //} bool CheckIsAccess(int maze[] , Pos cur) { if (cur._row >= 0 && cur._row < N && cur._col >= 0 && cur._col < N && maze[cur._row][cur._col] == 0) { return true; } return false; } bool GetMazePath(int maze[] , Pos entry, stack<Pos>& paths) { paths.push(entry); maze[entry._row][entry._col] = 2; while (!paths.empty()) { Pos cur = paths.top(); Pos next = cur; if (cur._row == N-1) { return true; } //上 next._row -= 1; if (CheckIsAccess(maze, next)) { paths.push(next); maze[next._row][next._col] = 2; continue; } //下 next = cur; next._row += 1; if (CheckIsAccess(maze, next)) { paths.push(next); maze[next._row][next._col] = 2; continue; } //左 next = cur; next._col -= 1; if (CheckIsAccess(maze, next)) { paths.push(next); maze[next._row][next._col] = 2; continue; } //右 next = cur; next._col += 1; if (CheckIsAccess(maze, next)) { paths.push(next); maze[next._row][next._col] = 2; continue; } //出栈栈顶位置,进行回溯 Pos tmp = paths.top(); maze[tmp._row][tmp._col] = 3; paths.pop(); } return false; } int main() { int mazeArray = { 0 }; InitMaze(mazeArray); PrintMaze(mazeArray); stack<Pos> paths; Pos entry = { 2, 0 }; bool ret = GetMazePath(mazeArray, entry, paths); if (ret) { cout << "成功走出迷宫" << endl; PrintMaze(mazeArray); } return 0; }
相关文章推荐
- 数据结构与算法JavaScript - 链表
- 数据结构实验之栈四:括号匹配
- 支付宝前端架构专家梁文森(绝云)与你探讨算法与数据结构
- 数据结构与算法JavaScript
- SDUT 2142 数据结构实验之图论二:基于邻接表的广度优先搜索遍历
- 为什么hash作为内存使用的经典数据结构?
- 算法+数据结构的本质
- POJ 3468 A Simple Problem with Integers 数据结构+线段树+区间更新+区间求和
- java数据结构之二叉树
- 数据结构(一)创建并遍历线性列表
- 数据结构二 顺序表的创建
- C语言-数据结构-栈运用实例-计算器源代码
- HDU 1754 I Hate It 数据结构+单点修改+区间极值
- HDU 1166 敌兵布阵 数据结构+树状数组+(单点更新区间求和)
- 数据结构之线段树
- java数据结构(循环链表)
- java数据结构(顺序表)
- 数据结构之树状数组
- 算法总结:【线段树+扫描线】&矩形覆盖求面积/周长问题(HDU 1542/HDU 1828)
- 数据结构1 「在线段树中查询一个区间的复杂度为 $O(\log N)$」的证明