求解迷宫问题(不是最佳路径)
#include<stdio.h>
#define MaxSize 50
#define M
10
#define N 10
int
m[m][N]={ //定义一个迷宫数组,0表示通道,1表示墙 {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
i; //行号 (当前方块)
int j;
//列号
int
di; //东南西北,四个可走的方向(0,1,2,3)
}st[MaxSize]; //另一个堆栈的方式---结构数组
int top=-1; //栈指针
void
mgpath(int x1,int y1,int x2,int y2)
//定义一个寻找同路的函数
(x1,y1)->(x2,y2)
{
int
i,j,k,di,find=0;
top++;
st[top].i=x1;st[top].j=y1;st[top].di=-1; //迷宫入口
while(top>-1)
{
i=st[top].i;j=st[top].j;di=st[top].di;
if(i==x2&&j==y2) //
{
printf("迷宫的通路如下\n");
for(k=0;k<=top;k++) //用for循环可以倒转输出栈元素
{
printf("[%d,%d]->",st[k].i,st[k].j);
if((k+1)%5==0)
printf("\n");
}
printf("\n");
return;//return直接结束了该函数
}
find=0;
while(di<4&&find==0) //寻找下一个可行的通路
{
di++;
switch(di)
{
case
0:i=st[top].i-1;j=st[top].j;break;
case
1:i=st[top].i;j=st[top].j+1;break;
case
2:i=st[top].i+1;j=st[top].j;break;
case
3:i=st[top].i;j=st[top].j-1;break;
}
if(mg[j]==0)
find=1; //find=1,证明找到了可行的通路
}
if(find==1)
{
st[top].di=di;
top++;
st[top].i=i;st[top].j=j;st[top].di=-1;
mg[j]=-1;
//另该位置不可再行,已经走过
}
else
{
mg[st[top].i][st[top].j]=0;
top--;
}
}
printf("迷宫没有出路\n");
}
void
main()
{
int x1,x2,y1,y2;
printf("please input the entrance
location:\n");
scanf("%d%d",&x1,&y1);
printf("please input the
exit
location:\n");
scanf("%d%d",&x2,&y2);
mgpath(x1,y1,x2,y2);
}

浙公网安备 33010602011771号