1.代码如下
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int vis[10005];
int k[10005];
int n, a, b;
void bfs()
{
queue<int> q;
q.push(a);
vis[a] = 0;
while (!q.empty())
{
int now = q.front();
q.pop();
if (now == b) return ;
int nxt = now + k[now];
if (1 <= nxt && nxt <= n && vis[nxt] == -1)
{
q.push(nxt);
vis[nxt] = vis[now] + 1;
}
nxt = now - k[now];
if (1 <= nxt && nxt <= n && vis[nxt] == -1)
{
q.push(nxt);
vis[nxt] = vis[now] + 1;
}
}
}
int main()
{
cin >> n >> a >> b;
for(int i = 1; i <= n; i++) cin >> k[i];
memset(vis, -1, sizeof vis);
bfs();
cout << vis[b];
return 0;
}