最少转弯问题

Problem Description

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

Input

输入有多组数据,每组数据的第一行为n和m,第2至n+1行为整个地图地形描述(0:空地;1:高山),第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
//标程:
#include<stdio.h>
#include<queue>
using namespace std;
struct ss
{
	int x,y,xx,yy,step;
};
queue<ss> q;
int p[110][110],n,m,x1,x2,y1,y2;
int dir[][2]={1,0,0,1,-1,0,0,-1};
void bfs()
{
     ss ans,temp;
	 while(!q.empty())
	 {
	     temp=q.front();
		 if(temp.x==x2 && temp.y==y2) { printf("%d\n",temp.step);   break;}
		 q.pop();
		 ss newx;
		 for(int i=0;i<4;i++)
		 {
			 newx.x=temp.x+dir[i][0];
			 newx.y=temp.y+dir[i][1];
		 if((newx.x>=1&&newx.x<=n && newx.y>=1&&newx.y<=m && !p[newx.x][newx.y]) )
		 {
                    if(newx.x!=temp.xx && newx.y!=temp.yy) newx.step=temp.step+1;
		    else  newx.step=temp.step;
		    newx.xx=temp.x, newx.yy=temp.y;
		    q.push(newx);
		 }
		 }
	 }
}


int main()
{
	//freopen("a.txt","r",stdin);
    while(scanf("%d%d",&n,&m)!=EOF)
	{
		int i,j;
		for(i=1;i<=n;i++)
			for(j=1;j<=m;j++)
				scanf("%d",&p[i][j]);
        scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
        while(!q.empty()) q.pop();
		ss ans,temp;
		temp.x=x1, temp.y=y1, temp.xx=x1, temp.yy=y1, temp.step=0;
		q.push(temp);
		bfs();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值