Files
python/TangDou/Bfs/3_QiGuaiDianTi.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

43 lines
949 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}