SSL P2325 最小转弯

本文介绍了一种算法,用于解决在一个给定矩阵中寻找从起点到终点的最短路径上的转弯次数问题。该算法基于回溯法,并通过记录状态来判断路径中的转弯情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目: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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值