最少步数
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
4
-
描述
-
这有一个迷宫,有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,10表示道路,1表示墙。
现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?
(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)
-
输入
-
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出
- 输出最少走几步。 样例输入
-
2 3 1 5 7 3 1 6 7
样例输出
-
12 11
-
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
广搜入门经典题,这个已经给出了迷宫就无需录入了,简单来说可以分为四步,
1:输入起点终点,
2:规定搜索的方向,
3:判断是否到达终点,没有到,继续搜索。
4:到达终点,输出最短距离。
#include<stdio.h>
#include<string.h>
int a[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,
};
struct node
{
int x,y,s;
};
int main()
{
struct node que [1000];
int book[10][10];
int next[4][2]={0,1,1,0,0,-1,-1,0};
int i,j,startx,starty,n,m,tx,ty,p,q,flag;
scanf("%d",&n);
while(n--)
{
memset(book,0,sizeof(book));
scanf("%d%d%d%d",&startx,&starty,&p,&q);
if(startx==p&&starty==q)//这个特别坑,再原点不动直接输出0.
{
printf("0\n");
continue;
}
int head=1,tail=2;
que[head].x=startx;
que[head].y=starty;
que[head].s=0;
flag=0;
while(tail>head)
{
for(i=0;i<4;i++)
{
tx=que[head].x+next[i][0];
ty=que[head].y+next[i][1];
if(tx<0||tx>8||ty<0||ty>8)
continue;
if(a[tx][ty]==0&&book[tx][ty]==0)
{
book[tx][ty]=1;
que[tail].x=tx;
que[tail].y=ty;
que[tail].s=que[head].s+1;
tail++;
}
if(tx==p&&ty==q)
{
flag=1;
break;
}
}
if(flag==1)
break;
head++;
}
printf("%d\n",que[tail-1].s);
}
return 0;
}