题目链接:https://www.luogu.com.cn/problem/P1135
题目大意:
- 给你 (k_i(1 le i le n)),从 (i) 能到达 (i - k_i) 和 (i + k_i),前提是目标数值在 (1 sim n) 范围内,求从 (a) 到 (b) 至少要几步。
解题思路:简单BFS,队列记录当前状态(位置),再开个dis数组记录起点到当前点的距离(步数)即可。
示例程序:
#include <bits/stdc++.h>
using namespace std;
int dis[220], n, a, b, k[220];
queue<int> que;
int main() {
cin >> n >> a >> b;
for (int i = 1; i <= n; i ++) cin >> k[i];
memset(dis, -1, sizeof(dis));
dis[a] = 0;
que.push(a);
while (!que.empty()) {
int u = que.front();
que.pop();
for (int i = -1; i <= 1; i += 2) {
int v = u + i * k[u];
if (v >= 1 && v <= n && dis[v] == -1) {
dis[v] = dis[u] + 1;
que.push(v);
}
}
}
cout << dis[b] << endl;
return 0;
}