Files
python/TangDou/Bfs/3_QiGuaiDianTi.cpp

43 lines
949 B
C++
Raw Normal View History

2025-08-30 18:35:01 +08:00
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
typedef pair<int,int> PII;
int n;
int a, b;
int k[N];
int st[N];
queue<PII> q;
int step = -1;
void bfs() {
//初始化队列
q.push({a, 0});
st[a] = 1;
while (q.size()) {
auto t = q.front();
q.pop();
if (t.first == b) {
step = t.second;
break;
}
int x = t.first + k[t.first];
if (x <= n && !st[x]) {
q.push({x, t.second + 1});
st[x] = 1;
}
x = t.first - k[t.first];
if (x >= 1 && !st[x]) {
q.push({x, t.second + 1});
st[x] = 1;
}
}
}
int main() {
//n是几层楼,a:从几层出发 ,b:到几层去
cin >> n >> a >> b;
for (int i = 1; i <= n; i++) cin >> k[i]; //记录每层楼的可以按下的数字
bfs();
printf("%d", step);
return 0;
}