数据结构之 栈应用---老鼠迷宫问题
2017-11-05 23:28
405 查看
老鼠迷宫问题是栈应用问题的一个入门,通过对满足要求的迷宫位置压栈,同时,将位置置为不可用,来实现对从迷宫入口到出口的路径寻找(非最优路径)。
下面是关键的代码:
其中矩阵的类使用的是之前自己写的矩阵模板类,栈使用的是STL的。pos类是用于表示矩阵位置的类。中间加入了一些打印的信息来显示整个过程。
当然,这个寻找路径的过程并不是最优的过程,结果也不是最优的路径,之后的队列应用会获得最佳结果。
下面是结果截图:
下面是关键的代码:
#include "myMatrix.cpp" #include <stack> #include "myStack_array.cpp" #include "pos.h" void generateMat(myMatrix<bool>& mat) { for (int ii = 0;ii < mat.rows(); ii++) { for (int jj = 0; jj < mat.cols(); jj++) { //mat(ii + 1, jj + 1) = (ii - jj < 0 ); //mat(1, jj + 1) = false; //mat(ii + 1, mat.cols()) = false; //mat(mat.rows(), jj + 1) = false; //mat(ii + 1, 1) = false; mat(ii + 1, jj + 1) = false; } } mat(2,2) = true; mat(3,2) = true; mat(3,3) = true; mat(3,4) = true; mat(3,5) = true; mat(3,6) = true; mat(3,6) = true; mat(4,6) = true; } bool findPath(myMatrix<bool>& mat) { bool flg = false; pos cur(2,2); if(!mat(cur.rows(),cur.cols())) { std::cout<<"return directly"<<std::endl; return false; } std::stack<pos> mst; mst.push(cur); mat(cur.rows(),cur.cols()) = false; pos end(mat.rows() - 1, mat.cols() - 1); pos offset[4]; offset[0] = pos(1,0); offset[1] = pos(0,1); offset[2] = pos(-1,0); offset[3] = pos(0,-1); int cnt = 0; cur = cur + offset[cnt]; while (cur != end) { if (mat(cur.rows(),cur.cols()))////为真表示可以到达 { std::cout<<cur<<" can be reached, pushed into stack"<<std::endl; mst.push(cur); mat(cur.rows(),cur.cols()) = false;///不再走这个位置 cnt = 0; cur = cur + offset[cnt]; } else { std::cout<<cur<<"can not be reached, backed"<<std::endl; cur = cur - offset[cnt]; cnt = cnt + 1; if (cnt < 4) { std::cout<<cur<<"still has place to test, offsetted"<<std::endl; cur = cur + offset[cnt]; } else { cnt = 0; if (!mst.empty()) { cur = mst.top(); mst.pop(); std::cout<<"no where to go, popped a position"<<std::endl; cur = cur + offset[cnt]; } else { std::cout<<"nothing to pop"<<std::endl; flg = false; break; } } } } if (cur == end && mat(cur.rows(), cur.cols())) { std::cout<<"reached last position and can be reached"<<std::endl; flg = true; mat(cur.rows(), cur.cols()) = false; mst.push(cur); } while (!mst.empty()) { cur = mst.top(); std::cout<<cur<<"\t"; mst.pop(); } return flg; } void main(void) { myMatrix<bool> mat(9,9); generateMat(mat); std::cout<<mat<<std::endl; if (findPath(mat)) { std::cout<<"Path Found"<<std::endl; } else { std::cout<<"Path Not Found"<<std::endl; } std::system("pause"); }
其中矩阵的类使用的是之前自己写的矩阵模板类,栈使用的是STL的。pos类是用于表示矩阵位置的类。中间加入了一些打印的信息来显示整个过程。
当然,这个寻找路径的过程并不是最优的过程,结果也不是最优的路径,之后的队列应用会获得最佳结果。
下面是结果截图:
相关文章推荐
- 栈的应用-迷宫问题-数据结构
- 数据结构之栈的应用(迷宫问题)
- 数据结构5————栈的应用2-非递归解决迷宫和马踏棋盘问题
- 经典数据结构之栈的应用-迷宫问题
- 数据结构之链式队列与链式栈的应用-球钟问题
- 数据结构之迷宫问题
- 数据结构实践——迷宫问题之图深度优先遍历解法
- (5)数据结构——栈应用——迷宫求解
- 数据结构课程设计——迷宫问题课程设计报告
- C语言 数据结构中求解迷宫问题实现方法
- 第六周--数据结构之自建算法库之迷宫问题(用队列)
- 算法:迷宫求解(栈的应用)-数据结构(8)
- 数据结构作业 迷宫问题 模拟 之基础的BFS DFS
- 数据结构——八方向探索迷宫问题解答
- 数据结构实践——迷宫问题之图深度优先遍历解法
- 数据结构之栈的应用----迷宫求解
- 看数据结构写代码(13)栈的应用(四) 迷宫求解
- [C++]数据结构课程设计:迷宫老鼠1.0
- 数据结构-栈应用-迷宫
- 数据结构(7)—栈的应用之迷宫求解