奇怪的电梯----bfs搜索

题目描述

呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第ii层楼(1 \le i \le N)(1≤i≤N)上有一个数字K_i(0 \le K_i \le N)Ki​(0≤Ki​≤N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3, 3 ,1 ,2 ,53,3,1,2,5代表了K_i(K_1=3,K_2=3,…)Ki​(K1​=3,K2​=3,…),从11楼开始。在11楼,按“上”可以到44楼,按“下”是不起作用的,因为没有-2−2楼。那么,从AA楼到BB楼至少要按几次按钮呢?

输入输出格式

输入格式:

共二行。

第一行为33个用空格隔开的正整数,表示N,A,B(1≤N≤200, 1≤A,B≤N)N,A,B(1≤N≤200,1≤A,B≤N)。

第二行为NN个用空格隔开的非负整数,表示K_iKi​。

输出格式:

一行,即最少按键次数,若无法到达,则输出-1−1。

输入输出样例

输入样例#1: 复制

5 1 5
3 3 1 2 5

输出样例#1: 复制

3

一般这样的求最小步数的题目要么是用搜索做,或者是图论做,一开始尝试过用dp做,但是蒟蒻能力有限做不出来,如果又大神会的话请评论一下思路哦。这里用bfs实现

#include<iostream>
#include<queue>
using namespace std;
int n, a, b;
int arr[202];//每层楼的编号
int res[202];//标记是否走过
typedef struct {
	int floor;
	int pushnum;//步数
}Floorn;
queue<Floorn> q;
int main()
{
	cin >> n >> a >> b;
	for (int k = 1; k <= n; k++)
	{
		cin >> arr[k];
	}
	Floorn q1, q2;
	q1.floor = a;
	q1.pushnum = 0;
	q.push(q1);
	res[a] = 1;
	while (!q.empty())
	{
		q2 = q.front();
		q.pop();
		if (q2.floor == b)
			break;
		int i = q2.floor + arr[q2.floor];
		if (i <= n&&res[i]==0)//如果电梯向上坐不出边界
		{
			q1.floor = i;
			q1.pushnum = q2.pushnum + 1;
			q.push(q1);
			res[i] = 1;
		}
		i = q2.floor - arr[q2.floor];
		if (i >= 1 && res[i] == 0)//如果电梯向下坐不出边界
		{
			q1.floor = i;
			q1.pushnum = q2.pushnum + 1;
			q.push(q1);
			res[i] = 1;
		}
	}
	if (q2.floor == b)
		cout << q2.pushnum << endl;
	else
		cout << -1 << endl;
	system("pause");
	return 0;
}

这里标记是否走过是因为这个题目虽然没有像迷宫题明显提出不能重复走,但是这里的电梯只有相同的上下两种方向,所以如果重复的话一定是步数会增多而且没有必要

猜你喜欢

转载自blog.csdn.net/scwMason/article/details/87180299