Sample Input
5 1 5 //5层楼 当前位置1楼 目标5楼 3 3 1 2 5 //1楼只可以按3,不能再下,到了4楼;4楼只能按2,到了2楼;2楼按3到了五楼 0
Sample Output
3 // 最少按了3次键
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n,s,e;
int map[210],judge[210];
struct node
{
int fl;
int step; //层数,步数
};
int bfs()
{
queue<node> q;
node pre,next;
pre.fl = s;
pre.step = 0;
q.push(pre);
judge[s] = 1;
memset(judge,0,sizeof(judge));
while (!q.empty())
{
pre = q.front();
q.pop();
if (pre.fl == e){
return pre.step;
break; }
for (int i = -1; i <= 1; i+=2)
{
next = pre; //保持pre不动,只动next
next.fl+=i*map[next.fl]; //map[next.fl]层数可以按的键
if(next.fl>n || next.fl<1 || judge[next.fl] == 1){
continue;}
next.step++;
q.push(next);
judge[next.fl] = 1;
}
}
return -1;
}
int main()
{
while(cin>>n && n){
cin>>s>>e;
for (int i = 1; i <= n; i++)
cin>>map[i];
cout<<bfs()<<endl;
}
return 0;
}

本文介绍了一种算法,该算法通过广度优先搜索(BFS)来确定从当前楼层到达目标楼层所需的最少按键次数。算法考虑了每层楼可按的不同按钮,并通过队列实现节点扩展,直至找到目标楼层。
2262

被折叠的 条评论
为什么被折叠?



