P1135 奇怪的电梯

在这里插入图片描述


#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<queue>

using namespace std;
const int N = 250;

int k[N];
int a, b, n;
int d[N];//***重点
//步数计算+是否走过判断
queue <int> q;

bool bfs(int f) {

	q.push(f);

	while (!q.empty())
	{
		int t = q.front();
//		printf("现在在%d楼\n", t);
		
//		ans++;

		q.pop();

		if (t == b)
			return true;

		if (!k[t]) continue;//k[t]==0的的特殊情况,不用走

		int f1 = t + k[t];
		int f2 = t - k[t];

		if (f1>=1&&f1<=n&&d[f1]==-1)
		{

			d[f1] = d[t] + 1;
			q.push(f1);
		}

		if (f2>=1&&f2<=n&&d[f2]==-1)
		{

			d[f2] = d[t] + 1;
			q.push(f2);
		}



	}
	return false;
}



int main() {
	scanf("%d %d %d", &n, &a, &b);//接受参数没啥好说的
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &k[i]);
	}

	memset(d, -1,sizeof d);//这里重置了数组d,
	//如果等于-1则没走过,如果等于除-1以外的数
	//比如d[b]=5 即从a楼到b楼所需要按按钮的最少次数为5,也就是最后的答案

	d[a] = 0;
	//起始楼层,手动设置成0
	//注意这里的赋值和memset函数不要写反了。。之前我犯过这样的错

	if (bfs(a))
		cout << d[b];
	else
		cout << -1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值