经过这段时间对于栈的学习,对于栈也有了一定的了解,所以想使用栈来实现一个简易的迷宫,来考察自己对于栈知识的掌握程度。
#define N 10
#define M 10 //在这里我们将行和列简单的定义为N,在这里同为10
struct postion //定义这个结构是为了更方便的使用和更改位置信息
{
postion(int x,int y)
:_x(x)
,_y(y)
{}
int _x;
int _y;
};
class Maze
{
public:
Maze(int map[][N]) //构造函数,使用一个二维数组来构建我们需要的迷宫
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
_map[i][j] = map[i][j];
}
}
}
void Painted() //打印迷宫
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
cout<<_map[i][j]<<" ";
}
cout << endl;
}
cout << endl;
}
bool IsPass(postion pos) //判断是否为一个通路,在我们设置的迷宫里,只有为1的路才是我们需要走的
{
if (_map[pos._x][pos._y] == 1)
{
return true;
}
else
return false;
}
bool IsExport(postion pos) //判断是否为出口,等我们行进到四个边上任意点的时候,就是出口了
{
if (pos._x <= 0 || pos._y <= 0)
{
return true;
}
return false;
}
bool Gomaze(postion _enter)
{
stack<postion> step; //在这里我们创建了一个栈
postion cur = _enter;
postion next = _enter;
step.push(_enter); //将入口压入栈里,表示此路我们已经走过了
while (1)
{
postion cur = step.top(); //设置此变量为栈顶元素,也就是上一步所在的位置
_map[cur._x][cur._y] = 2; //因为要区分已走过的路,我们将走过地方的元素设置为3
if (IsExport(cur)) //在这里判断如果为出口的化 就返回函数
{
return true;
}
next = cur; //接下来分别为上下左右通路的判断
next._x -= 1;
if (_map[next._x][next._y] == 1)//up
{
step.push(next);
continue;
}
next = cur;
next._x += 1;
if (_map[next._x][next._y] == 1)//down
{
step.push(next);
continue;
}
next = cur;
next._y -= 1;
if (_map[next._x][next._y] == 1)//left
{
step.push(next);
continue;
}
next = cur;
next._y += 1;
if (_map[next._x][next._y] == 1)//right
{
step.push(next);
continue;
}
_map[cur._x][cur._y] = 3; //在这里是判断假如这个点上下左右都不是通路,将它置为3,和其他点进行区分
step.pop(); //因上一个点的路为此点下一个点任何一方就不通,所以我们返回这个点,进行它四方的判断,寻求另外一个出路
}
}
protected:
int _map[M][N];
};
迷宫的设置和进行都在上面代码中,下面我们来试验一下,它是否可以运行,以及是否能够运行成功,0代表无关的路,1代表出路,2代表走过的路,3代表走过后发现没有出路返回上一个点的路。
int main()
{
int arr[10][10] = //在这里我们设置了这样一个迷宫,可以看出来有两个地方是有分歧路但是走不通的
{ {0,1,0,0,0,0,0,0,0,0}
, {0,1,0,0,0,0,0,0,0,0}
, {0,1,0,0,0,0,0,0,0,0}
, {0,1,0,0,0,0,0,0,0,0}
, {0,1,0,0,1,0,0,0,0,0}
, {0,1,0,0,1,0,0,0,0,0}
, {0,1,0,0,1,0,1,0,0,0}
, {0,1,1,1,1,1,1,0,0,0}
, {0,0,0,0,0,0,1,0,0,0}
, {0,0,0,0,0,0,1,0,0,0} };
Maze maze(arr);
postion enter(9, 6);
maze.Painted();
maze.Gomaze(enter);
maze.Painted();
getchar();
return 0;
}
在主函数中,我们将走之前和走之后的迷宫都打印出来进行对比。
由图中我们可以看出迷宫的确是按照我们预想的方式走了下去,这就实现了一个极为简易的迷宫。