迷宫初始化
自定义一个迷宫
#include<stdio.h>
typedef struct position
{
int x;//初始横坐标
int y;//初始纵坐标
}P;
typedef struct rout
{
P p[100];
int len=0;
}R;
int a[10][10]={ {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} };
方法
随机走迷宫,如果碰到死胡同,则标记该点并退回到上一位置
void run(R &r)
{
while(1){
int X=r.p[r.len].x;
int Y=r.p[r.len].y;
int flag=0;
if(a[X+1][Y]==0&&flag==0) {a[X+1][Y]=2;r.len++;r.p[r.len].x=X+1;r.p[r.len].y=Y;flag=1;printf("下 ");}//向下移动
if(a[X-1][Y]==0&&flag==0) {a[X-1][Y]=2;r.len++;r.p[r.len].x=X-1;r.p[r.len].y=Y;flag=1;printf("上 ");}//向上移动
if(a[X][Y-1]==0&&flag==0) {a[X][Y-1]=2;r.len++;r.p[r.len].x=X;r.p[r.len].y=Y-1;flag=1;printf("左 ");}//向左移动
if(a[X][Y+1]==0&&flag==0) {a[X][Y+1]=2;r.len++;r.p[r.len].x=X;r.p[r.len].y=Y+1;flag=1;printf("右 ");}//向右移动
if(r.p[r.len].x==8&&r.p[r.len].y==8) break;
if(!flag)
{
printf("堵住");
a[X][Y]=1;//堵死的路
r.p[r.len].x=NULL;
r.p[r.len].y=NULL;
r.len--;
}
}
}
运行测试
将初始坐标设置为(1,1)
int main()
{
rout r;
r.p[0].x=1;
r.p[0].y=1;
run(r);
for(int i=0;i<r.len;i++)
{
printf("(%d,%d) ",r.p[i].x,r.p[i].y);
}
}