这是一道洛谷的黄题哈,这道题可以用广搜或者队列来写,我这边是使用广搜来写,主要思路:我要么往上要么往下所以用广搜则比较好写,bfs里面只需要判断是往上还是往下即可这边不多说放AC代码
#include <bits/stdc++.h>
using namespace std;
int n,a,b;
int c[205];
bool vis[205];
struct node{
int x,step;
};
int bfs(int x){
node now,pos,next;
now.x = x,now.step=0;
queue<node>q;
q.push(now);
while(!q.empty()){
pos = q.front();
q.pop();
if(pos.x == b){
return pos.step;
}
int f = -1;
for(int i = 0;i < 2; i++){
int bx = pos.x + c[pos.x]*f;
f = f*-1;
if(bx < 0 || bx > n) continue;
if(vis[bx] == 1) continue;
vis[bx]=1;
next.x=bx;next.step=pos.step+1;
q.push(next);
}
}
return -1;
}
int main(){
cin >> n >> a >> b;
for(int i = 1; i <= n; i++){
cin >> c[i];
}
vis[a]=1;
cout << bfs(a);
return 0;
}