题目链接: P1135 奇怪的电梯 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
dfs
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 210;
int arr[N];
bool st[N]; //每一层只走一次
int n, a, b,cnt=0;
int res = 1e9;
void dfs(int x,int cnt)
{
if (cnt > res) return;
if (x > n || x < 1) return;
if (x == b)
{
res = min(res, cnt);
return;
}
if (x + arr[x] <= n && !st[x + arr[x]])
{
st[x + arr[x]] = true;
dfs(x + arr[x], cnt + 1);
st[x + arr[x]] = false;
}
if (x - arr[x] > 0&&! st[x- arr[x]])
{
st[x - arr[x]] = true;
dfs(x - arr[x], cnt + 1);
st[x - arr[x]] = false;
}
}
int main()
{
cin >> n >> a >> b;
for (int i = 1; i <= n; i++)
cin >> arr[i];
dfs(a,cnt);
st[a] = true;
if (res == 1e9)
cout << "-1" << endl;
else cout << res << endl;
return 0;
}