时间限制:3000 ms | 内存限制:65535 KB
难度:4
输入
第一行输入一个整数n(0
输出
输出最少走几步。
样例输入
2 3 1 5 7 3 1 6 7
样例输出
12 11
描述
这有一个迷宫,有0~8行和0~8列:
1,1,1,1,1,1,1,1,1
1,0,0,1,0,0,1,0,1
1,0,0,1,1,0,0,0,1
1,0,1,0,1,1,0,1,1
1,0,0,0,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,1,0,0,1
1,1,0,1,0,0,0,0,1
1,1,1,1,1,1,1,1,1
0表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
#include
#include
#define max 1000
int mg[9][9]={
{1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,1,0,1},
{1,0,0,1,1,0,0,0,1},
{1,0,1,0,1,1,0,1,1},
{1,0,0,0,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1},
};
typedef struct
{
int i;
int j;
int pre;
}box;
typedef struct
{
box data[max];
int front,rear;
}qu;
bool mgpath(int a,int b,int c,int d);
bool en(qu *&s,box e)
{
if(s->rear==max-1)
return false;
s->rear++;
s->data[s->rear]=e;
return true;
}
bool de(qu *&s,box &e)
{
if(s->front==s->rear)
return false;
s->front++;
e=s->data[s->front];
return true;
}
int length=0;
int main()
{
int n,a,b,c,d;
scanf("%d",&n);
while(n--)
{
length=0;
scanf("%d%d%d%d",&a,&b,&c,&d);
mgpath(a,b,c,d);
printf("%d\n",length);
}
return 0;
}
bool mgpath(int a,int b,int c,int d)
{
int i,j,di,i1,j1,p,q;
qu *s;
box path[max],e;
s=(qu*)malloc(sizeof(qu));
s->front=s->rear=-1;
int mg[9][9]={ // 初始化迷宫
{1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,1,0,1},
{1,0,0,1,1,0,0,0,1},
{1,0,1,0,1,1,0,1,1},
{1,0,0,0,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1},
};
e.i=a; e.j=b; e.pre=-1;
en(s,e);
mg[a][b]=-1;
while(s->front!=s->rear)
{
de(s,e);
i=e.i; j=e.j;
if(i==c&&j==d)
{
q=s->front;
while(q!=0)// 算出 迷宫步数
{
//p=q;
q=s->data[q].pre;
length++;
}
//printf("%d\n",length);
return true;
}
else
{
for(di=0;di<4;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)
{
e.i=i1; e.j=j1; e.pre=s->front;
en(s,e);
mg[i1][j1]=-1;
}
}
}
}
return false;
}