最少步数
时间限制: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
<string.h>
03.
using
namespace
std;
04.
05.
bool
maze[9][9]=
06.
{
07.
{1,1,1,1,1,1,1,1,1},
08.
{1,0,0,1,0,0,1,0,1},
09.
{1,0,0,1,1,0,0,0,1},
10.
{1,0,1,0,1,1,0,1,1},
11.
{1,0,0,0,0,1,0,0,1},
12.
{1,1,0,1,0,1,0,0,1},
13.
{1,1,0,1,0,1,0,0,1},
14.
{1,1,0,1,0,0,0,0,1},
15.
{1,1,1,1,1,1,1,1,1}
16.
};
17.
bool
vis[9][9];
18.
int
minStep=90,step,startx,starty,endx,endy;
19.
int
dir[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
20.
21.
//行,列,已走步数
22.
void
dfs(
int
x,
int
y,
int
step)
23.
{
24.
if
(x==endx&&y==endy)
25.
{
26.
if
(step<minStep)minStep=step;
27.
return
;
28.
}
29.
if
(maze[x][y]||vis[x][y])
return
;
30.
vis[x][y]=1;
31.
int
xt,yt;
32.
for
(
int
i=0;i<4;i++)
33.
{
34.
xt=x+dir[i][0];
35.
yt=y+dir[i][1];
36.
dfs(xt,yt,step+1);
37.
}
38.
vis[x][y]=0;
39.
}
40.
41.
int
main()
42.
{
43.
int
n;
44.
cin>>n;
45.
while
(n--)
46.
{
47.
cin>>startx>>starty>>endx>>endy;
48.
minStep=90;step=0;
49.
memset
(vis,0,
sizeof
(vis));
50.
dfs(startx,starty,0);
51.
cout<<minStep<<endl;
52.
}
53.
return
0;
54.
}