HDU 1548(A strange lift)

廣搜題,每次搜索上下兩個方向即可。

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 205;

int N; //樓層數
int s, e; //起點,終點
int num[MAXN]; //每層可以上下的樓層數
int vis[MAXN]; //訪問情況
int step[MAXN]; //到達各層時的步數

//廣搜
int BFS()
{
	memset(vis, 0, sizeof(vis));
	memset(step, 0, sizeof(step));

	queue<int> q;
	vis[s] = 1;
	step[s] = 0;
	q.push(s);
	while (!q.empty())
	{
		int now = q.front();
		q.pop();
		if (now == e)
		{
			return step[now];
		}
		for (int i = 0; i < 2; i++) //搜索上下兩個方向
		{
			int next;
			if (i == 0)
				next = now + num[now];
			else
				next = now - num[now];
			if (next < 1 || next > N)
				continue;
			if (!vis[next])
			{
				vis[next] = 1;
				q.push(next);
				step[next] = step[now] + 1;
			}
		}
	}
	return -1;
}

int main()
{
	while (cin >> N)
	{
		if (N == 0)
			break;
		
		cin >> s >> e;
		for (int i = 1; i <= N; i++)
		{
			cin >> num[i];
		}
		cout << BFS() << endl;
	}
	return 0;
}

繼續加油。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章