BFS错了3个,求助
查看原帖
BFS错了3个,求助
570430
Latty_楼主2022/8/5 11:21

代码如下

#include<bits/stdc++.h>
using namespace std;
int n,a,b;
int arr[205];
int vis[205];
struct node{
    int h,step;
};
void bfs(){
    queue<node> q;
    q.push({a,0});
    while(!q.empty()){
        node n1=q.front();
        q.pop();
        if(n1.h==b){
            cout<<n1.step;
            return;
        }
        for(int i=1;i<=2;i++){
            if(i%2){
                if(n1.h+arr[n1.h]>n||vis[n1.h+arr[n1.h]])continue;
                    vis[n1.h+arr[n1.h]]=1;
                    q.push({n1.h+arr[n1.h],n1.step+1});
            }
            else{
                if(n1.h-arr[n1.h]<1||vis[n1.h-arr[n1.h]])continue;
                    vis[n1.h-arr[n1.h]];
                    q.push({n1.h-arr[n1.h],n1.step+1});
            }
        }
    }
    
}
int main(){
    cin>>n>>a>>b;
    for(int j=1;j<=n;j++){
        cin>>arr[j];
    }
    
    bfs();
    return 0;
}
2022/8/5 11:21
加载中...