您的位置:首页 > 理论基础 > 数据结构算法

数据结构之 栈应用---老鼠迷宫问题

2017-11-05 23:28 405 查看
老鼠迷宫问题是栈应用问题的一个入门,通过对满足要求的迷宫位置压栈,同时,将位置置为不可用,来实现对从迷宫入口到出口的路径寻找(非最优路径)。

下面是关键的代码:

#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类是用于表示矩阵位置的类。中间加入了一些打印的信息来显示整个过程。

当然,这个寻找路径的过程并不是最优的过程,结果也不是最优的路径,之后的队列应用会获得最佳结果。

下面是结果截图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构