bfs宽搜

Problem - B - Codeforces

#include <bits/stdc++.h>
using namespace std;
 
typedef long long LL;
typedef pair<int,int> PII;
 
const int N=1e4+10;
int q[N], hh,tt;
int d[N];
int n,m;

int bfs(int u)
{
	memset(d,-1,sizeof d);
	q[0]=u;
	d[u]=0;
	while(hh<=tt){
		int t=q[hh++];
		if(t==m) return d[t];
		int j=t-1;
		if(j>=0 && j<=10000 && d[j]==-1){
			q[++tt]=j;
			d[j]=d[t]+1;
		}
		j=t*2;
		if(j>=0 && j<=10000 && d[j]==-1){
			q[++tt]=j;
			d[j]=d[t]+1;
		}
	}
}

void solve()
{
	cin>>n>>m;
	int cnt=0;
	if(n>=m) cnt=n-m;
	else {
		cnt=bfs(n);
	}
	cout<<cnt<<'\n';
	
}
 
int main()
{
	int T;
//	cin>>T;
	T=1;
	while(T--){
		solve();
	}
	return 0;
}

D-虫洞操纵者_牛客周赛 Round 55 (nowcoder.com)(最短路)

#include <bits/stdc++.h>
using namespace std;

typedef long long LL;
typedef pair<int,int> PII;

const int N=1e3+10;
int g[N][N],d[N][N];
PII q[N*N];
int n;

int bfs()
{
	int hh=0,tt=0;
	q[0]={1,1};
	d[1][1]=1;//表示这个点已经到过,未到的点为0.最后结果多一步. 
	int dx[4]={-1,0,1,0}, dy[4]={0,1,0,-1};
	while(hh<=tt)
	{
		auto t=q[hh++];
		if(t.first ==n && t.second==n) return d[n][n]-1;
		for(int i=0; i<4; i++){
			int x=t.first+dx[i], y=t.second+dy[i];
			if(x<1 || x>n || y<1 || y>n || g[x][y]==1){
				if(i==0) for(int j=t.first; j<=n+1; j++){
					if(g[j][y]==1 || j==n+1){
						x=j-1;
						break;
					} 
				}
				if(i==2) for(int j=t.first; j>=0; j--){
					if(g[j][y]==1 || j==0) {
						x=j+1;break;	
					}
				}
				if(i==1) for(int j=t.second; j>=0; j--){
					if(g[x][j]==1 || j==0){
						y=j+1; break;
					} 
				}
				if(i==3) for(int j=t.second; j<=n+1; j++){
					if(g[x][j]==1 || j==n+1){
						y=j-1;break;
					} 
				}
			}
			if(d[x][y]==0){
				d[x][y]=d[t.first][t.second]+1;
				q[++tt]={x,y};
			}
		}

	}
	return -1;
}

void solve()
{
	cin>>n;
	for(int i=1; i<=n; i++){
		for(int j=1; j<=n; j++){
			cin>>g[i][j];
		}
	}
	cout<<bfs();
}	

int main()
{
	int T;
//	cin>>T;
	T=1;
	while(T--){
		solve();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值