位址:
https://www.luogu.com.cn/problem/P1135
描述:
代碼:
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
//n表示總共有幾層,a是起點,b是終點
const int N = 210;
int n, a, b;
//從起點到第x層需要幾步
int d[N];
//表示第i層允許上下幾層
int k[N];
queue<int> q;
void bfs(int a, int b) {
q.push(a);
d[a] = 0;
while (!q.empty()) {
auto temp = q.front();
q.pop();
int x = temp + k[temp];
if (x <= n && d[x] == -1) {
q.push(x);
d[x] = d[temp] + 1;
}
x = temp - k[temp];
if (x>=1 && d[x] == -1) {
q.push(x);
d[x] = d[temp] + 1;
}
}
}
int main() {
cin >> n >> a >> b;
memset(d, -1, sizeof d);
for (int i = 1; i <= n; i++) {
cin >> k[i];
}
bfs(a, b);
cout << d[b];
return 0;
}