代码如下
#include<queue>
#include<cstdio>
#include<iostream>
using namespace std;
typedef struct{
int now;
int step;
}floor;
int to[205];
queue<floor> que;
int flag[205];
int n,start,_end;
void BFS(int sf,int ef){
floor flr;
flr.now = sf;
flr.step = 0;
que.push(flr);
flag[sf] = 1;
while (!que.empty()){
flr = que.front();
que.pop();
if(flr.now == ef) break;
int h = flr.now +to[flr.now];
if(h<=n && flag[h] == 0){
flr.now = h;
flr.step = flr.step+1;
que.push(flr);
flag[flr.now] = 1;
}
h= flr.now - to[flr.now];
if(h>0 && flag[h] == 0){
flr.now = h;
flr.step = flr.step+1;
que.push(flr);
flag[flr.now] = 1;
}
}
if(flr.now == ef) cout<<flr.step;
else cout<<"-1";
}
int main(){
cin>>n>>start>>_end;
for (int i=1;i<=n;i++)
cin>>to[i];
BFS(start,_end);
return 0;
}