[BFS]最小轉彎問題

最小轉彎問題

Description
給出一張地圖,這張地圖被分爲 n×m(n,m<=100)個方塊,任何一個方塊不是平地就是高山。平地可以通過,高山則不能。現在你處在地圖的(x1,y1)這塊平地,問:你至少需要拐幾個彎才能到達目的地(x2,y2)?你只能沿着水平和垂直方向的平地上行進,拐彎次數就等於行進方向的改變(從水平到垂直或從垂直到水平)的次數。例如:如圖 1,最少的拐彎次數爲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

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


代碼

#include<stdio.h>
#include<iostream>
using namespace std;
const int dx[5]={0,1,-1,0,0};
const int dy[5]={0,0,0,1,-1};
int n,m,a[10005][10005],x1,y1,x2,y2,st[1005][4];
void bfs(){
	int head=0,tail=1;
	st[1][1]=x1;st[1][2]=y1;
	do{
		head++;
		for(int i=1;i<=4;i++){ //四個方向
			int x=st[head][1]+dx[i];
			int y=st[head][2]+dy[i];
			while(x>=1 and x<=n and y>=1 and y<=m and a[x][y]==0){ //如果沒有出界而且能走,就一直走
				if(x==x2 and y==y2){ //判斷是不是滿足條件
					printf("%d",st[tail][3]);
					return ;
				}
				tail++;
				a[x][y]=1;
				st[tail][1]=x;
				st[tail][2]=y;
				st[tail][3]=st[head][3]+1; //是st[head][3]的轉彎數加一
				x+=dx[i];
				y+=dy[i]; 
			}
		}
	}while(head<tail);
} 
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
	 for(int j=1;j<=m;j++)
	  scanf("%d",&a[i][j]);
	scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
	bfs();
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章