深搜求优化
查看原帖
深搜求优化
865793
better_Z楼主2023/6/11 14:01
#include<iostream>
#include<cstdio>
using namespace std;

int n,a,b;
int k[210];
int ans = -1;
bool flag[210];

void dfs(int now, int times){

    if(now == b) {
        ans = times;
        return;
    }

    for(int i=-1; i<=1; i+=2){
        int next = now - (i*k[now]);
        if(next > n || next < 1 || flag[next])continue;
        flag[next] = true;
        dfs(next, times+1);
        flag[next] = false;
    }
}

int main(){

    cin>>n>>a>>b;

    for(int i=1;i<=n;i++)cin>>k[i];

    flag[a] = true;
    dfs(a, 0);

    printf("%d", ans);

    return 0;
}
2023/6/11 14:01
加载中...