题解
2024-12-07 20:43:35
发布于:浙江
7阅读
0回复
0点赞
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
struct node{
int x,cnt;
};
int a[205];
bool vis[205];
int main(){
int n,A,b;
cin >> n >> A >> b;
for(int i=1; i<=n; i++) cin >> a[i];
queue<node> q;
q.push({A,0});
while(!q.empty()){
node f=q.front();
vis[f.x]=1;
// cout<<f.x<<" ";
q.pop();
if(f.x==b){
cout << f.cnt;
return 0;
}
if(f.x-a[f.x]>0&&!vis[f.x-a[f.x]]) q.push({f.x-a[f.x],f.cnt+1}),vis[f.x-a[f.x]]=1;
if(f.x+a[f.x]<=n&&!vis[f.x+a[f.x]]) q.push({f.x+a[f.x],f.cnt+1}),vis[f.x+a[f.x]]=1;
}
cout<<-1;
return 0;
}
【时间复杂度】
O(N)
【预计得分】
100pts
这里空空如也
有帮助,赞一个