#define _CRT_SECURE_NO_WARNINGS
//这里的迷宫用二位数组表示,1表示能走通其他表示不能走通
#include<iostream>
#include<stack>
using namespace std;
struct Seat//储存坐标
{
Seat(int x, int y) :
_x(x),
_y(y)
{}
int _x;
int _y;
};
#define ROW 10
#define COL 10
class Maze
{
public:
Maze(int map[][COL])//
{
for (size_t i = 0; i < ROW; i++)
for (size_t j = 0; j < COL; j++)
{
_map[i][j] = map[i][j];
}
}
void PrintMap()//打印迷宫
{
for (size_t i = 0; i < ROW; i++)
{
for (size_t j = 0; j < COL; j++)
{
cout << _map[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
bool IsPass(const Seat& s)//判断是否为通路,仅当该点的值为1时能走通
{
if (_map[s._x][s._y] == 1)
{
return true;
}
return false;
}
bool IsExit(const Seat & s)//判断是否为出口,仅当坐标不在迷宫内为出口
{
if (s._x<0||s._x>=ROW||s._y<0||s._y>=COL)
{
return true;
}
return false;
}
bool Pass(Seat &curPos)//走迷宫过程
{
if (!IsPass(curPos))
{
cout << "输入口非法" << endl;
return false;
}
stack<Seat> s;//定义栈储存走过的路径
s.push(curPos);
while (!s.empty())//栈不为空时一直走
{
Seat curPos = s.top();//当前坐标放在栈顶
if (IsExit(curPos))
{
return true;
}
_map[curPos._x][curPos._y] = 2;//将入口标记为2,就不会重复走
Seat up(curPos);
up._x -= 1;//先向上面走
if (IsPass(up))
{
s.push(up);
_map[up._x][up._y] = 2;//做标记
continue;
}
Seat left(curPos);//在向左边走
left._y -= 1;
if (IsPass(left))
{
s.push(left);
_map[left._x][left._y] = 2;//做标记
continue;
}
Seat right(curPos);
right._y += 1;//向右边走
if (IsPass(right))
{
s.push(right);
_map[right._x][right._y] = 2;//做标记
continue;
}
Seat down(curPos);
down._x += 1;//向下走
if (IsPass(down))
{
s. push(down);
_map[down._x][down._y] = 2;//做标记
continue;
}
//四个方向都不能走时,将标记改为3
_map[curPos._x][curPos._y] = 3;
//弹出栈顶保存坐标,退回上一步,向其他方向走
s.pop();
}
return false;
}
private:
int _map[ROW][COL];
};
int main()
{
int maparray[ROW][COL] = {
{ 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 1, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 } };
Maze m(maparray);
Seat s(9, 6);//入口
m.PrintMap();
m.Pass(s);
m.PrintMap();
system("pause");
return 0;
}
输出结果如下:
一张
上面的是开始时的迷宫,下面的是走完之后并弹出所有栈中元素的迷宫,
另截取一张刚走完的迷宫,
此时迷宫刚好走到出口。