地址:
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;
}