HDOJ1548(BFS)

大意:n层楼,坐电梯从a层到b层。第i层有一个数Ki,可以上到i+Ki层,可以下到i-K层。求最少几次能从a到b层。

分析:BFS水题。

代码

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int n, a, b;
int k[205];
int e[205];
queue<int>q;
int bfs(int x, int y)
{
	memset(e, 0, sizeof(e));
	while (!q.empty())
		q.pop();
	int sum = 0;
	q.push(x);
	e[x] = 1;
	while (!q.empty()) 
	{
		if (q.front() == y)
			return e[y]-1;
		int m = k[q.front()] + q.front();
		if (m > 0 && m <= n&&!e[m])
		{
			q.push(m);
			e[m] = e[q.front()]+1;
		}
		int t = q.front() - k[q.front()];
		if (t > 0 && t <= n&&!e[t])
		{
			q.push(t);
			e[t] = e[q.front()] + 1;
		}
		q.pop();
	}
	return -1;
}
int main()
{
	while (scanf("%d", &n) != EOF&&n)
	{
		scanf("%d%d", &a, &b);
		for (int i = 1; i <= n; i++)
			scanf("%d", &k[i]);
		printf("%d
", bfs(a, b));
	}
	return 0;
}


原文地址:https://www.cnblogs.com/nickqiao/p/7583414.html