题目:http://blog.youkuaiyun.com/qq_35786326/article/details/78836913
题意:
求在一个矩阵中的最短路径方案中的转弯次数。
分析:
原身:Oliver的救援(http://blog.youkuaiyun.com/qq_35786326/article/details/78796604)。
在其上面稍作改动即可(装作自己用了10分钟改完了)。
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#define LL long long
using namespace std;
inline LL read(){
LL d=0,f=1;char s=getchar();
while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
return d*f;
}
int f=0,t,w,a=0,b,c,d,n,m,x[105][105],state[10001][2],father[10001],dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
void cao(int l)//采用回溯法处理拐弯数
{
if(father[l]==0) return;
else cao(father[l]);
if(state[l][0]-state[father[l]][0]==0) f=2; else f=1;
if(father[father[l]]==0) a=f;
if(a!=f) t++//t为统计变量,a=f;//f为判断当前的走法(横着or竖着),a为判断上一次的走法,方便看出是否有转弯
}
void bfs()//跟Oliver的救援同理
{
int head,tail,x1,y1;
head=0;tail=1;state[1][0]=a;state[1][1]=b;father[1]=0;x[a][b]=1;
do
{
head++;
for(int i=0;i<4;i++)
{
x1=state[head][0]+dx[i];y1=state[head][1]+dy[i];
if(x[x1][y1]==0&&x1>0&&x1<=n&&y1>0&&y1<=m)
{
x[x1][y1]=1;
tail++;
father[tail]=head;
state[tail][0]=x1;
state[tail][1]=y1;
if(x1==c&&y1==d) {cao(tail);tail=0;return;}
}
}
}while(head<tail);
return;
}
int main()
{
n=read();m=read();
int i,j;char s;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
x[i][j]=read();
a=read();b=read();c=read();d=read();
bfs();
printf("%d",t);
return 0;
}