Description
给出一张地图,这张地图被分为 n×m(n,m<=100)个方块,任何一个方块不是平地就是高山。平地可以通过,高山则不能。现在你处在地图的(x1,y1)这块平地,问:你至少需要拐几个弯才能到达目的地(x2,y2)?你只能沿着水平和垂直方向的平地上行进,拐弯次数就等于行进方向的改变(从水平到垂直或从垂直到水平)的次数。
例如:如样例,最少的拐弯次数为5。
Input
第 1行:n m 第 2至n+1行:整个地图地形描述(0:空地;1:高山), 如图,第2行地形描述为:1 0 0 0 0 1 0 第3行地形描述为:0 0 1 0 1 0 0 …… 第n+2行:x1 y1 x2 y2 (分别为起点、终点坐标)
Output
最少的拐弯次数
Sample Input
5 7
1 0 0 0 0 1 0
0 0 1 0 1 0 0
0 0 0 0 1 0 1
0 1 1 0 0 0 0
0 0 0 0 1 1 0
1 3 1 7
Sample Output
5
思路
这里可以bfs枚举出每一个可以到达的点及其最小转弯数量,那么我们枚举时注意因为是最小转弯数量所以需要枚举每一个方向的每一个长度,具体见代码。
code:
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
bool a[1005][1005];
short int q[4][2]={{0,1},{0,-1},{-1,0},{1,0}},n,m,s,x,y;
struct f{
short int x,y,z;
} o,o2;
queue<f> p;
void bfs()
{
while (p.size())
{
o=p.front();
p.pop();
for (int i=0;i<4;i++)
{
for (int j=1;;j++)
{
int dx=o.x+q[i][0]*j,dy=o.y+q[i][1]*j;//枚举长度
if (dx==x&&dy==y)
{
cout<<o.z;
return;
}
if (dx<1||dy<1||dx>n||dy>m||a[dx][dy]) break;//走不动就退出该方向
a[dx][dy]=1;
o2.x=dx,o2.y=dy,o2.z=o.z+1;
p.push(o2);
}
}
}
return;
}
int main()
{
cin>>n>>m;
for (int i=1;i<=n;i++) for (int j=1;j<=m;j++) cin>>a[i][j];
cin>>o.x>>o.y;
p.push(o);
cin>>x>>y;
bfs();
return 0;
}