问题描述:
给定一个M*N的迷宫图,求一条从指定入口和出口的迷宫路径。假设迷宫图如图所示:M=N=6的迷宫图
数据组织:
为了表示迷宫,设置一个数组mg,其中每个元素表示一个方块的状态,为0表示方块是通道,为1表示方块是障碍物(不可走),为了算法方便,一般在迷宫的外围加一条围墙,例如上图的迷宫表示为(由于迷宫四周加了一道围墙,故mg数组的行数的列数均加上2)
迷宫栈的声明:
typedef struct // 定义数据类型
{
int i,j,di;
} Box;
typedef struct // 定义栈
{
Box data[10000];
int top;
} StType;
具体实现:
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef struct // 定义数据类型
{
int i,j,di;
} Box;
typedef struct // 定义栈
{
Box data[10000];
int top;
} StType;
int mg[6][6]= // 迷宫地图
{
{1,1,1,1,1,1},{1,0,0,0,1,1},
{1,0,1,0,0,1},{1,0,0,0,1,1},
{1,1,0,0,0,1},{1,1,1,1,1,1}
};
void InitStack(StType *&s) // 初始化
{
s=(StType *)malloc(sizeof(StType));
s->top=-1;
}
bool Push(StType *&s,Box e) // 出栈
{
if(s->top==100-1)
return false;
s->top++;
s->data[s->top]=e;
return true;
}
bool Pop(StType *&s,Box &e) // 进栈
{
if(s->top==-1)
return false;
e=s->data[s->top];
s->top--;
return true;
}
bool Gettop(StType *s,Box &e) // 得到栈顶元素
{
if(s->top==-1)
return false;
e=s->data[s->top];
return true;
}
bool Empty(StType *s) // 判断是否为空
{
return (s->top==-1);
}
bool mgpath(int xi,int yi,int xe,int ye,int road) // 具体实现查找路径
{
Box path[10000],e;
int i,j,di,i1,j1,k,maproad=0;
bool Find;
StType *st;
InitStack(st);
e.i=xi,e.j=yi,e.di=-1;
Push(st,e);
mg[xi][yi]=-1;
while(!Empty(st))
{
Gettop(st,e);
i=e.i,j=e.j,di=e.di;
if(i==xe&&j==ye)
{
printf("第%d条迷宫路径如下:\n",road);
k=0;
while(!Empty(st))
{
Pop(st,e);
path[k++]=e;
}
while(k>=1)
{
k--;
printf("(%d,%d) ",path[k].i,path[k].j);
maproad++;
if((k+2)%5==0)
printf("\n");
}
printf("\n");
printf("路径长度为:%d\n",maproad);
free(st);
return true;
}
Find=false;
while(di<4&&!Find) // 控制查找的方向
{
di++;
switch(di)
{
case 0:
i1=i-1;
j1=j;
break;
case 1:
i1=i;
j1=j+1;
break;
case 2:
i1=i+1;
j1=j;
break;
case 3:
i1=i;
j1=j-1;
break;
}
if(mg[i1][j1]==0)Find=true;
}
if(Find)
{
st->data[st->top].di=di;
e.i=i1;
e.j=j1;
e.di=-1;
Push(st,e);
mg[i1][j1]=-1;
}
else
{
Pop(st,e);
mg[e.i][e.j]=0;
}
}
free(st);
return false;
}
int main() // 主函数
{
if(!mgpath(1,1,4,4,1))
printf("该迷宫没有解\n");
return 0;
}
思维开拓:
如果你理解了上述的迷宫问题,理解了具体的思路设计,那么试试这个迷宫吧,下面的这个迷宫要求找出所有的路径,找到最短路径并输出,快来动动脑哦,(趁热打铁,熟能生巧)相信这个难不倒聪明的你哦!!!!