讲解:
一。设置地图 用 0 表示可通,用1表示障碍物(不可通)
二。思想:就是让 人 在迷宫里面向上,向下,向左,向右(这四个顺序,你也可以随意安排向上,向下,向左,向右的顺序)的走动,每一次走都要让人走没有走过的地方,所以我们在这里将人走过的地方设置为1, 在此我们假设,人向上走,一直走,知道碰到 1(障碍物),则人先向下,发现下方的那个地方是数字1(即为障碍物),于是人选择向左,发下左边的那个地方是0,然后人向左,并将走过的地方的数字变为1,然后就这样一直判断,人下一次走的地方数字是否为0,若为0,则继续前进,若为1,则尝试,另一个方向。倘若我们发现向上,向下,向左,向右的这些地方数字都是1,那么我们就 回溯 ,人就退到自己的上一步的位置,若还是向上,向下,向左,向右的这些地方数字都是1,则继续回溯,直到找到 你设置 的出口。
三。工具:需要 运用到 栈 (先进后出) 和 二维数组。
#include<stdio.h>
#include<stdlib.h>
#define M 10
int map[M][M]={
{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},
};
int map1[M][M]={
{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},
};
int top =0;
typedef struct{
int i;
int j;
} Route;
void up(Route route[])
{
map[route[top].i][route[top].j]=1;
top++;
route[top].i=route[top-1].i-1;
route[top].j=route[top-1].j;
}
void down(Route route[])
{
map[route[top].i][route[top].j]=1;
top++;
route[top].i=route[top-1].i+1;
route[top].j=route[top-1].j;
}
void left(Route route[])
{
map[route[top].i][route[top].j]=1;
top++;
route[top].i=route[top-1].i;
route[top].j=route[top-1].j-1;
}
void right(Route route[])
{
map[route[top].i][route[top].j]=1;
top++;
route[top].i=route[top-1].i;
route[top].j=route[top-1].j+1;
}
void back(Route route[])
{
map[route[top].i][route[top].j]=1;
top--;
}
int map_route(Route route[],int x,int y)
{
do
{
if(map[route[top].i-1][route[top].j]==0)
up(route);
else
{
if(map[route[top].i+1][route[top].j]==0)
down(route);
else
{
if(map[route[top].i][route[top].j-1]==0)
left(route);
else
{
if(map[route[top].i][route[top].j+1]==0)
right(route);
else
back(route);
}
}
}
if(route[top].i==x&&route[top].j==y)
break;
}while(top>=0);
return 0;
}
int match(Route route[],int i,int j)
{
for(int val=0;val<=top;val++)
{
if(i==route[val].i&&j==route[val].j)
{
return 1;
break;
}
}
return 0;
}
int main()
{
Route route[M*M];
route[top].i=8;
route[top].j=8;//设置起点坐标
int x=1,y=1;//设置终点坐标
if(map[x][y]==1||map[route[top].i][route[top].j]==1)
{
printf("出口点或者入口点设置不合理");
exit(0);
}
map_route(route,x,y);
printf("迷宫走之前\n");
for(int i =0;i<M;i++)
{
for(int j=0;j<M;j++)
{
printf("%d ",map1[i][j]);
}
printf("\n");
}
printf("\n");
if(top<0)
printf("无解");
else
{
printf("迷宫走之后\n");
for(int i =0;i<M;i++)
{
for(int j=0;j<M;j++)
{
if(match(route,i,j))
printf("* ");
else
printf("%d ",map1[i][j]);
}
printf("\n");
}
}
return 0;
}