HUD 1548 BFS 换了一种实现方式

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main()
{
	int n, a, b;
	vector<int > v(1000);
	vector<bool > visited(1000);
	vector<int > step(1000);
	vector<int > f(10000);

	while (true)
	{
		cin>>n;
		if (n == 0)
			break;

		cin>>a>>b;

		for (int i = 1; i <= n; i++)
		{
			cin>>v[i];
			visited[i] = false;
			f[i] = 0;
		}
		if (a == b)
		{
			cout<<"0"<<endl;
			continue;
		}
		step.clear();
		step.push_back(a);

		int i = 0;
		bool flag = false;
		while (i != step.size())
		{
			if (!visited[step[i]])
			{
				if (step[i] == b)
				{
					flag = true;
					break;
				}
				if (step[i] - v[step[i]] > 0 && !visited[step[i] - v[step[i]]] )
				{
					step.push_back(step[i] - v[step[i]]);
					f[step.size() - 1] = f[i] + 1;
					//cout << step[i] - v[step[i]] << endl;
				}
				if (step[i] + v[step[i]] <= n && !visited[step[i] + v[step[i]]] )
				{
					step.push_back(step[i] + v[step[i]]);
					f[step.size() - 1] = f[i] + 1;
					//cout << step[i] + v[step[i]] << endl;
				}
				visited[step[i]] = true;
			}
			i++;
		}

		if (flag == true)
		{
			cout<<f[i]<<endl;
		}
		else
		{
			cout<<"-1"<<endl;
		}
	}
}

你可能感兴趣的:(HUD 1548 BFS 换了一种实现方式)