题目:
给出一张地图,这张地图被分为 n×m(n,m<=100)个方块,任何一个方块不是平地就是高山。平地可以通过,高山则不能。现在你处在地图的(x1,y1)这块平地,问:你至少需要拐几个弯才能到达目的地(x2,y2)?你只能沿着水平和垂直方向的平地上行进,拐弯次数就等于行进方向的改变(从水平到垂直或从垂直到水平)的次数。例如:如图 1,最少的拐弯次数为5。 
思路:
用广搜,之后回溯统计转弯次数。
代码:
#include<cstdio>
int b,f,m,n,a[101][101],state[11000][3],s,father[11000],x,y,px,py,best;
short dx[5]={0,1,0,-1,0},dy[5]={0,0,1,0,-1};
char c;
bool check(int x,int y)
{
if (1>x||x>n||1>y||y>m||a[x][y]==1) return false;
return true;
}
void print(int x)//回溯
{
if (father[x]==0) return;
else print(father[x]);
if(state[x][1]-state[father[x]][1]==0) f=2; else f=1;
if(father[father[x]]==0) b=f;
if(b!=f) s++,b=f;
}
void bfs()
{
int tail,head;
state[1][1]=x;state[1][2]=y;state[1][3]=0;tail=1;head=0;
do
{
head++;
for (int i=1;i<=4;i++)
{
if(check(state[head][1]+dx[i],state[head][2]+dy[i]))
{
tail++;
father[tail]=head;
state[tail][1]=state[head][1]+dx[i];
state[tail][2]=state[head][2]+dy[i];
a[state[tail][1]][state[tail][2]]=1;
if (state[tail][1]==px&&state[tail][2]==py)
{
print(tail);
tail=0;
}
}
}
}
while (head<tail);
}
int main()
{
scanf("%d",&n);scanf("%d",&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",&x,&y,&px,&py);
bfs();
printf("%d",s);
}
本文介绍了一种使用广度优先搜索(BFS)解决地图上寻找最短路径的问题,并通过回溯算法统计行进中拐弯次数的方法。具体场景是在一张由平地和高山组成的地图上,从起点出发到达终点所需的最小拐弯次数。
266





