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; }