DFS版
#include <bits/stdc++.h>
using namespace std;
int N;
int num[205];
bool vis[205];
int beg, end;
int minn = 0x7f7f7f7f;
void dfs(int now, int step)
{
if (now == end)
{
minn = min(minn, step);
return;
}
if (step > minn)
{
return;
}
vis[now] = true;
if (now + num[now] <= N && vis[now + num[now]] == false)
{
dfs(now + num[now], step + 1);
}
if (now - num[now] >= 1 && vis[now - num[now]] == false)
{
dfs(now - num[now], step + 1);
}
vis[now] = false;
}
int main()
{
cin >> N >> beg >> end;
for (int i = 1; i <= N; i++)
{
cin >> num[i];
}
dfs(beg, 0);
if (minn == 0x7f7f7f7f)
{
cout << -1 << endl;
}
else
{
cout << minn << endl;
}
}
BFS版
#include <bits/stdc++.h>
using namespace std;
int N;
int num[205];
bool vis[205];
int beg, end;
queue< pair<int, int> > q;
void bfs(int start)
{
q.push(make_pair(start, 0));
while (!q.empty())
{
pair<int, int> fir = q.front();
q.pop();
int lastFloor = fir.first;
if (lastFloor == end)
{
cout << fir.second << endl;
exit(0);
}
vis[lastFloor] = true;
if (lastFloor + num[lastFloor] <= N && vis[lastFloor + num[lastFloor]] == false)
{
q.push(make_pair(lastFloor + num[lastFloor], fir.second + 1));
}
if (lastFloor - num[lastFloor] >= 1 && vis[lastFloor - num[lastFloor]] == false)
{
q.push(make_pair(lastFloor - num[lastFloor], fir.second + 1));
}
}
cout << -1 << endl;
}
int main()
{
cin >> N >> beg >> end;
for (int i = 1; i <= N; i++)
{
cin >> num[i];
}
bfs(beg);
}