如果理解了栈,并会应用栈来解决问题,这个迷宫的问题并不难。
主要就是不断的探路,将可行路径入栈,走不下去就出栈,继续由栈顶元素寻找新路。
代码写的不算完美,但答案是正确的。不过按这个方法是没法找最优解的。
/*求解迷宫问题
2013.8.31
by无名*/
#include <iostream>
using namespace std;
const int M = 8;
const int N = 8;
const int MaxSize = 80;
int mg[M + 2][N + 2] =
{ {1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
struct
{
int hang; //当前方块的行号
int lie; //当前方块的列号
} st[MaxSize]; //定义栈
int top = -1; //初始化栈顶指针
class Mgpath
{
public:
void find_the_way();
void show_the_way();
};
void Mgpath :: find_the_way()
{
for(int i = 0; i < 81; i++) //初始化栈
{
st[i].hang = 0;
st[i].lie = 0;
}
top++;
st[top].hang = 1; //起点入栈
st[top].lie = 1;
while((st[top].hang != 8) || (st[top].lie != 8))
{ //当栈顶元素不是终点
if(mg[st[top].hang - 1][st[top].lie] == 0)
//如果向上可走
{
top++; //将向上一点入栈
st[top].hang = st[top - 1].hang - 1;
st[top].lie = st[top - 1].lie;
mg[st[top].hang][st[top].lie] = -1;
//标记已走过
continue; //跳入下次循环,忽略以下语句
}
else if(mg[st[top].hang][st[top].lie + 1] == 0)
//如果向右可行
{
top++; //将向右一点入栈
st[top].hang = st[top - 1].hang;
st[top].lie = st[top - 1].lie + 1;
mg[st[top].hang][st[top].lie] = -1;
//标记已走过
continue;
}
else if(mg[st[top].hang + 1][st[top].lie] == 0)
//如果向下一点可行
{
top++;
st[top].hang = st[top - 1].hang + 1;
st[top].lie = st[top - 1].lie;
mg[st[top].hang][st[top].lie] = -1;
//标记已走过
continue;
}
else if(mg[st[top].hang][st[top].lie - 1] == 0)
//向左一点
{
top++;
st[top].hang = st[top - 1].hang;
st[top].lie = st[top - 1].lie - 1;
mg[st[top].hang][st[top].lie] = -1;
//标记已走过
continue;
}
else
//出栈
{
mg[st[top].hang][st[top].lie] = -1;
//标记为-1,表明该点不可行
top--;
}
}
}
void Mgpath :: show_the_way()
{
int i;
for(i = 0;i <= top; i++)
{
cout << "(" << st[i].hang << "," << st[i].lie << ")" << endl;
}
}
int main()
{
Mgpath MyMg;
MyMg.find_the_way();
MyMg.show_the_way();
return;
}