用的BFS ac了三个点 但其他点都爆内存了
请各位大佬调教!!!
#include <bits/stdc++.h>
using namespace std;
struct node{
int x,step;
};
queue<node> q;
int n,a,b,h[300],ans=-1;
int st[300];
int main(){
cin>>n>>a>>b;
for(int i=1;i<=n;i++){
cin>>h[i];
}
q.push({a,0});
st[a]=1;
while(!q.empty()){
node temp=q.front();
q.pop();
int nx=temp.x+h[temp.x];
if(nx<=n and !st[nx]){
q.push({nx,temp.step+1});
}
nx=temp.x-h[temp.x];
if(nx>=1 and !st[nx]){
q.push({nx,temp.step+1});
}
if(temp.x==b){
ans=temp.step;
}
}
cout<<ans;
return 0;
}