题目大意
有一个电梯,每一次层能走的楼层数是一定的,但是可以决定向上或向下,问从A到B楼层最短需要的移动次数是多少,不可能到达就放回-1。
思路
其实这就是一个用BFS来求最短路问题,看看代码就很容易懂。
代码
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
int a[1000000];//a来存出每一层的数据
int n;
int g[1000000];//g来存储楼层到起始楼层需要的移动次数
void bfs(int st, int en) {
queue<int> q;
if (st == en) {//如果楼层相等要g[st]要值位1,为了和输出相对应
g[en] = 1;
return;
}
q.push(st);
g[st] = 1;
while (!q.empty()) {
int t = q.front();
q.pop();
if (t == en)
break;
if (t - a[t]>0 && t - a[t] <= n&&!g[t-a[t]]) {
q.push(t - a[t]);
g[t - a[t]] = g[t]+1;
}
if (t + a[t] > 0 && t + a[t] <= n&&!g[t + a[t]]) {
q.push(t + a[t]);
g[t + a[t]] = g[t]+1;
}
}
}
int main() {
int A, B;
while (cin >> n&&n) {
cin >> A >> B;
memset(g, 0, sizeof(g));//每一次都要初始化!注意了
for (int i = 1; i <= n; i++) {//这里用i=1开始来和题目的意思对应
scanf("%d", &a[i]);
}
bfs(A, B);
cout << g[B]-1 << "\n";//由于bfs中有多了一个单位所以再这减一,也符合找不到输出-1的要求
}
}