https://www.luogu.com.cn/problem/P1135
题目描述
呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第ii层楼(1 \le i \le N)(1≤i≤N)上有一个数字K_i(0 \le K_i \le N)Ki(0≤Ki≤N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3, 3 ,1 ,2 ,53,3,1,2,5代表了K_i(K_1=3,K_2=3,…)Ki(K1=3,K2=3,…),从11楼开始。在11楼,按“上”可以到44楼,按“下”是不起作用的,因为没有-2−2楼。那么,从AA楼到BB楼至少要按几次按钮呢?
输入格式
共二行。
第一行为33个用空格隔开的正整数,表示N,A,B(1≤N≤200, 1≤A,B≤N)N,A,B(1≤N≤200,1≤A,B≤N)。
第二行为NN个用空格隔开的非负整数,表示K_iKi。
输出格式
一行,即最少按键次数,若无法到达,则输出-1−1。
输入输出样例
输入 #1复制
5 1 5 3 3 1 2 5
输出 #1复制
3
题解:一般BFS写法,判断当前位置向上走和向下走是否合法,如果合法,放入队列中,标记已经走过。不合法不做处理。
一开始忘记了初始化和vis标记,意识里标记过了,忘记写上,卡了好半天。
#include <stdio.h>
#include <string.h>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node
{
int x,step;
} w,l;
bool vis[210];
int a[205];
void bfs(int s, int e,int n)
{
memset(vis,0,sizeof(vis));
vis[s] = 1;
w.x = s;
w.step = 0;
queue<node>q;
q.push(w);
int flag = 0;
while(!q.empty()){
w = q.front();
q.pop();
if(w.x == e){
flag = 1;
printf("%d\n",w.step);
return ;
}
int tu = w.x + a[w.x];
int td = w.x - a[w.x];
// cout << tu << " " << td <<endl;
if(tu <= n && vis[tu] == 0){
l.x = tu;
l.step = w.step + 1;
vis[tu] = 1;
q.push(l);
}
if(td >= 1 && vis[td] == 0){
l.x = td;
l.step = w.step + 1;
vis[td] == 1;
q.push(l);
}
}
if(flag == 0){
printf("-1\n");
}
return ;
}
int main()
{
int n,s,e;
// cin >> n >> s >> e;
scanf("%d%d%d",&n,&s,&e);
for(int i = 1; i <= n; i ++){
scanf("%d",&a[i]);
}
if(s == e) printf("0\n");
else
bfs(s,e,n);
return 0;
}