最少步数
时间限制: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
解析:由于边上全部都是1,所以我们在这里就不用考虑越界这种情况了,个人觉得,广搜较好做些。下面贴出广搜代码。
具体代码如下:
#include<stdio.h> #include<deque> #include<iostream> using namespace std; typedef struct { int x,y,step; }T; int zou[10]={-1,1,0,0,0,0,-1,1}; int fun(T a,T b) { int map[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}; deque<T> q; T m; int i; while(1) { if(a.x==b.x&&a.y==b.y) return a.step; a.step++; for(i=0;i<4;i++) { m.x=a.x+zou[i];m.y=a.y+zou[i+4]; if(map[m.x][m.y]==0) { m.step=a.step;map[m.x][m.y]=1; q.push_back(m); } } a=q.front(); q.pop_front(); } } int main() { T a,b; int n; scanf("%d",&n); while(n--) { scanf("%d%d%d%d",&a.x,&a.y,&b.x,&b.y); a.step=0; printf("%d\n",fun(a,b)); } return 0; }
-
第一行输入一个整数n(0<n<=100),表示有n组测试数据;