#include "mystack.h"
#include "position.h"
//随便给定一个迷宫,有障碍的地方赋值为1,无障碍的地方复制为0
//从左边进,右边出。在此迷宫中即在maze[1][0]进在maze[5][6]出
int maze[7][7] = { 1,1,1,1,1,1,1,
0,0,1,0,0,0,1,
1,0,1,0,1,1,1,
1,0,0,0,1,0,1,
1,0,1,0,0,0,1,
1,0,1,0,1,0,0,
1,1,1,1,1,1,1 };
int main()
{
position now(1, 0); //定义当前位置,即位于数组中的位置
//定义怎样移动·····················
position move[4];
move[0].x = 0; move[0].y = 1; //向右移动
move[1].x = 0; move[1].y = -1; //向左移动
move[2].x = 1; move[2].y = 0; //向下移动
move[3].x = -1; move[3].y = 0; //向上移动
maze[1][0] = 1; //阻止返回入口
LinkStack<position> path; //用于存储路径
path.push(now); //存入起点
//开始移动················
int choose = 0; int lastchoose = 3;
while (now.x != 5 || now.y != 6) //当不是出口时
{
int newx, newy;
while (choose <= lastchoose) //按照向右左下上的顺序寻找下一个可移动的位置
{
newx = now.x + move[choose].x;
newy = now.y + move[choose].y;
if (maze[newx][newy] == 0)
break;
else
choose++;
}
if (choose <= lastchoose)//移动成功
{
now.x = newx; now.y = newy; //更新当前位置
path.push(now); //记录路径
maze[newx][newy] = 1; //防止倒退
choose = 0; //使之继续循环,寻找下一个可移动的位置,
}
else //没有找到可移动的位置,则回溯
{
if (path.empty())
return false;
else
{
position old;
old = path.pop(); //在路径中删除当前位置
now = path.gettop(); //返回上一位置
}
}
}
path.showstack(); //显示倒路径(这条路径是倒的)
LinkStack<position> ver;
while (!path.empty())
{
ver.push(path.pop());
}
cout << endl << endl;
ver.showstack(); //显示路径(真正的路径)
now = ver.pop();
position next;
while (!ver.empty())
{
next = ver.pop();
if (now.x == next.x&&next.y>now.y)
cout << "向右" << endl;
if (now.x == next.x&&next.y<now.y)
{
cout << "向左" << endl;
}
if (now.x>next.x&&next.y == now.y)
{
cout << "向上" << endl;
}
if (now.x<next.x&&next.y == now.y)
{
cout << "向下" << endl;
}
now = next;
}
system("pause");
return 0;
}
用栈实现的一个迷宫自动寻找出路。