P1135 奇怪的电梯
代码实现
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef struct
{
int floor;
int step;
} QElement;
queue<QElement> q;
const int N = 300;
int n, a, b;
int s[N];
int t[N]={0};
void bfs(int a)
{
int i;
QElement e1, e2;
e1.floor = a;
e1.step = 0;
q.push(e1);
t[a] = 1;
while (!q.empty())
{
e2 = q.front();
q.pop();
if (e2.floor == b)
break;
i = e2.floor + s[e2.floor];
if (i <= n && t[i] == 0)
{
e1.floor = i;
e1.step = e2.step + 1;
q.push(e1);
t[i] = 1;
}
i = e2.floor - s[e2.floor];
if (i >= 1 && t[i] == 0)
{
e1.floor = i;
e1.step = e2.step + 1;
q.push(e1);
t[i] = 1;
}
}
if (e2.floor == b)
cout << e2.step << endl;
else
cout << -1 << endl;
}
int main()
{
cin >> n >> a >> b;
for (int i = 1; i <= n; i++)
cin >> s[i];
bfs(a);
return 0;
}