A strange lift HDU - 1548 (超详细!!!!)

#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
int dir[2] = { -1,1 }; //只有两个方向移动
int n, s, e, i;
int lift[250], vis[250];//vis记录位置
struct node
{
	//移动,步数
	int x, step;
}a;
int BFS()
{
	queue<node>q;//定义队列
	vis[s] = 1;//将初始位置标记
	q.push((node) { s, 0 });//起点入队,步数为0,这个方法很特殊,拿小本本记下来
	while (!q.empty())
	{
		//队列不为空
		a = q.front();//取出队首
		q.pop();//队首元素出队
		if (a.x == e)
			return a.step;//终点,直接返回最小步数
		for (i = 0; i < 2; i++)
		{
			//两个方向搜索
			int tx = a.x + dir[i] * lift[a.x];//下一个点的位置
			if (tx > 0 && tx <= n && !vis[tx])
			{
				//该点存在且没有被访问过
				vis[a.x] = 1;//标记该点
				q.push((node){tx,a.step+1});//从该点开始,并步数加1
			}
		}
	}
	return -1;//到不了
}

int main()
{
	while (~scanf("%d",&n)&&n)
	{
		scanf("%d%d",&s,&e);
		for (i = 1; i <= n; i++)
		scanf("%d",&lift[i]);
		memset(vis, 0, sizeof(vis));//注意重置(知道我的意思就行)
		printf("%d\n",BFS());
	}
}

 

相关文章:

  • 2021-07-11
  • 2022-12-23
  • 2022-12-23
  • 2021-10-10
  • 2021-12-09
  • 2022-12-23
  • 2021-11-29
  • 2021-06-25
猜你喜欢
  • 2021-05-18
  • 2022-12-23
  • 2021-09-29
  • 2022-02-23
  • 2022-02-02
  • 2022-12-23
相关资源
相似解决方案