【BFS】奇怪的电梯

Description

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

Input

输入文件共有二行,第一行为三个用空格隔开的正整数,表示N,A,B(1≤N≤200, 1≤A,B≤N),第二行为N个用空格隔开的正整数,表示Ki。

Output

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

Sample Input

5 1 5
3 3 1 2 5

Sample Output

3

Code:

#include <iostream>
#include <queue>

#define SIZE 210

using namespace std;

struct node
{
	int n, step;
};

int num[SIZE], n, a, b, res = -1, t;
bool v[SIZE], f;
queue<node> q;
node tempnode;

void bfs(void) // 广搜过程 
{
	if (q.empty()) // 队列空,返回 
	{
		return;
	}
	t = q.front().n + num[q.front().n]; // 上↑
	if ((!v[t]) && ((t > 0) && (t <= n)))
	{
		if (t == b) // 到达终点
		{
			f = true;
			res = q.front().step + 1;
			return;
		}
		tempnode.n = t;
		tempnode.step = q.front().step + 1;
		q.push(tempnode); // 入队
		v[t] = true; // 防止重复查找
	}
	if (f)
	{
		return;
	} // 下面那个\为误打,不影响编译(Dev-C++5.11)
	t = q.front().n - num[q.front().n];\ // 下↓
	if ((!v[t]) && ((t > 0) && (t <= n)))
	{
		if (t == b)
		{
			f = true;
			res = q.front().step + 1;
			return;
		}
		tempnode.n = t;
		tempnode.step = q.front().step + 1;
		q.push(tempnode);
		v[t] = true;
	}
	q.pop(); // 出队
	bfs(); // 继续搜
	return;
}

int main()
{
	int i;
	
	cin >> n >> a >> b;
	
	for (i = 1; i <= n; i++) // 输入
	{
		cin >> num[i];
	}
	
	if (a == b)
	{
		cout << 0 << endl;
		return 0;
	}
	tempnode.n = a;
	tempnode.step = 0;
	q.push(tempnode); // 起点入队
	bfs(); // 开始广搜
	
	cout << res << endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/80789850