求调

P1649 [USACO07OCT] Obstacle Course S

FROGXx @ 2024-12-01 12:33:49


#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define N 105
ll n;
int dir_x[4]={0,-1,0,1};
int dir_y[4]={1,0,-1,0};
int sx,sy,ex,ey;
struct node{
    int nx,ny;
    int tim;
    int dir;
};
char mis[N][N];
bool b[N][N];
int ans=999999;
queue <node> q;
void bfs(int x,int y,int tme,int dr){
    node t;t.nx=x;t.ny=y;t.tim=tme;t.dir=dr;
    q.push(t);
    while(!q.empty()){
        auto [fx,fy,ft,fr] =q.front();
        if(fx==ex && fy==ey){
            ans=min(ans,ft);
            q.pop();
            continue;
        }
        for(int i=-1;i<=1;i++){
            if(fx+dir_x[(fr+4+i)%4]<1 || fx+dir_x[(fr+4+i)%4]>n || fy+dir_y[(fr+4+i)%4]<1 || fy+dir_y[(fr+4+i)%4]>n || mis[fx+dir_x[(fr+4+i)%4]][fy+dir_y[(fr+4+i)%4]]=='x' || b[fx+dir_x[(fr+4+i)%4]][fy+dir_y[(fr+4+i)%4]]){
                continue;
            }
            q.push({fx+dir_x[(fr+4+i)%4],fy+dir_y[(fr+4+i)%4],ft+abs(i),(fr+4+i)%4});
            b[fx+dir_x[(fr+4+i)%4]][fy+dir_y[(fr+4+i)%4]]=1;
        }
        q.pop();
    }
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>mis[i][j];
            if(mis[i][j]=='A'){
                sx=i;sy=j;
            }
            if(mis[i][j]=='B'){
                ex=i;ey=j;
            }
        }
    }
    for(int i=1;i<=4;i++){
        memset(b,0,sizeof(b));
        bfs(sx,sy,0,i);
    }
    cout<<ans<<endl;
    return 0;
}

|