最少步数
时间限制:
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
-
-
#include<iostream>
02.
#include<queue>
03.
#include <stdio.h>
04.
#include <string>
05.
using
namespace
std;
06.
07.
int
fx[4] = {1, -1, 0, 0}, fy[4] = {0, 0, 1, -1};
08.
09.
struct
node{
10.
int
row;
11.
int
col;
12.
int
step;
13.
}l, p, q;
14.
15.
int
a[9][9]=
16.
{
17.
1,1,1,1,1,1,1,1,1,
18.
1,0,0,1,0,0,1,0,1,
19.
1,0,0,1,1,0,0,0,1,
20.
1,0,1,0,1,1,0,1,1,
21.
1,0,0,0,0,1,0,0,1,
22.
1,1,0,1,0,1,0,0,1,
23.
1,1,0,1,0,1,0,0,1,
24.
1,1,0,1,0,0,0,0,1,
25.
1,1,1,1,1,1,1,1,1
26.
};
27.
int
map[9][9];
28.
29.
int
bfs(
int
r1,
int
c1,
int
r2,
int
c2)
30.
{
31.
queue <node> Q;
32.
int
i;
33.
int
map[9][9] = {0};
34.
l.row = r1;
35.
l.col = c1;
36.
l.step = 0;
37.
Q.push(l);
38.
while
(!Q.empty())
39.
{
40.
p = Q.front();
41.
Q.pop();
42.
if
(p.row == r2 && p.col == c2)
43.
{
44.
// while(!Q.empty())
45.
// Q.pop();
46.
return
p.step;
47.
}
48.
for
(i = 0; i < 4; i++)
49.
{
50.
q.row = p.row + fx[i];
51.
q.col = p.col + fy[i];
52.
if
(q.row >= 0 && q.row < 9 && q.col >= 0 && q.col < 9 && a[q.row][q.col] == 0 && map[q.row][q.col] == 0)
53.
{
54.
map[q.row][q.col] = 1;
55.
q.step = p.step + 1;
56.
Q.push(q);
57.
}
58.
}
59.
}
60.
}
61.
62.
int
main(
void
)
63.
{
64.
int
step;
65.
int
r1, c1, r2, c2, n;
66.
cin>>n;
67.
for
(
int
i = 0; i < n; i++)
68.
{
69.
cin>>r1>>c1>>r2>>c2;
70.
step = bfs(r1, c1, r2, c2);
71.
cout<<step<<endl;
72.
}
73.
return
0;
74.
}
-
第一行输入一个整数n(0<n<=100),表示有n组测试数据;