SSLOJ 1338.逃亡路径【bfs】

本文探讨了一个在n*m网格中寻找从(1,1)到(n,m)的最短路径的问题,仅允许以日字形移动。通过深度优先搜索(DFS)算法尝试解决,并讨论了时间效率问题及剪枝优化策略。

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


题目:

传送门


题意:

有一张 n ∗ m n*m nm的图,我的起点在 1 , 1 1,1 1,1
我只能走“日”字
问到达 n , m n,m n,m的最短路径不同方案数有多少


分析:

我先跑了一遍 d f s dfs dfs,然后喜闻乐见的 T L E TLE TLE
233 233 233,因为对 b f s bfs bfs真的不熟,所以试图剪枝来减少耗时
我发现 T T T的原因是因为每个点都有经过多次的可能,所以要通过记录方案数避免重复经过,再一想,我好想只会用 b f s bfs bfs实现这个吖 . . . ... ...真是尴尬


代码:

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
#define LL long long 
#define LZX 9901
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 dx[8]={1,2,2,1,-1,-2,-2,-1},dy[8]={-2,-1,1,2,2,1,-1,-2};
int tf[105][105],ans=0,ms=2147483647/3;
int n=read(),m=read();
void dfs(int x,int y,int p)
{
	if(p>ms) return;
	if(x==n&&y==m)
	{
		if(p<ms) ms=p,ans=1; else if(p==ms) ans++,ans%=LZX;
		return;
	}
	for(int i=0;i<8;i++)
	{
		int yx=x+dx[i],yy=y+dy[i];
		if(yx<=0||yx>n||yy<=0||yy>m) continue;
		if(p+1>tf[yx][yy]) continue;
		tf[yx][yy]=p+1;
		dfs(yx,yy,p+1);
	}
	return;
}
int main()
{
	memset(tf,0x7f,sizeof(tf));
	tf[1][1]=1;
	dfs(1,1,0);
	cout<<ans;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值