Problem1778--最少转弯问题

1778: 最少转弯问题

Time Limit: 1.000 Sec  Memory Limit: 128 MB
Submit: 504  Solved: 219
[Submit] [Status] [Web Board] [Creator:]

Description

给出一张地图,这张地图被分为n×mn,m<=100)个方块,任何一个方块不是平地就是高山。平地可以通过,高山则不能。现在你处在地图的(x1,y1)这块平地,问:你至少需要拐几个弯才能到达目的地(x2,y2)?你只能沿着水平和垂直方向的平地上行进,拐弯次数就等于行进方向的改变(从水平到垂直或从垂直到水平)的次数。例如:如图1,最少的拐弯次数为5


Input

1行:n   m
2n+1行:整个地图地形描述(0:空地;1:高山),
如(图1)第2行地形描述为:1 0 0 0 0 1 0
          
3行地形描述为:0 0 1 0 1 0 0
           ……
n+2行:x1 y1 x2 y2 (分别为起点、终点坐标)


Output

s (即最少的拐弯次数)


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

HINT

#include <bits/stdc++.h>
using namespace std;
int dx[5]={0,-1,0,1,0};
int dy[5]={0,0,1,0,-1};
int main()
{
int n,m;
int a[1001][101];
int x,y,x2,y2;
int sum[101][101];

cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>a[i][j];
}
}
cin>>x>>y>>x2>>y2;
sum[x][y]=-1;
int b[101][110]={0};
b[x][y]=1;
    int x3;
    int y3;
int h=0;
int t=1;
int x1=x;
int l[101];
int z[101];
l[1]=x;
z[1]=y;
int y1=y;
while(h<t)
{
h++;
for(int i=1;i<=4;i++)
{
x3=l[h]+dx[i];
y3=z[h]+dy[i];
while(b[x3][y3]==0&&a[x3][y3]==0&&x3>0&&x3<=n&&y3>0&&y3<=m)
{
    t++;
l[t]=x3;
z[t]=y3;
sum[x3][y3]=sum[l[h]][z[h]]+1;
b[x3][y3]=1; 
if(x3==x2&&y3==y2)
    {
    cout<<sum[x3][y3];
}
x3+=dx[i];
y3+=dy[i];
}
}
}
}

Source/Category


[Submit] [Status]