1AC1TLE其他全WA求助

P1649 [USACO07OCT] Obstacle Course S

LHY20221231 @ 2023-06-15 17:05:47

#include<bits/stdc++.h>
using namespace std;
int n,sum=0,dx,dy,zdx,zdy,qdx,qdy;
char mg[101][101];
int xa[4]={1,-1,0,0};
int ya[4]={0,0,1,-1};
struct stm{
    int x,y,step;
}t;
int pd[101][101]={-1};
queue <stm> q;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>mg[i][j];
            if(mg[i][j]=='A'){
                qdx=i;
                qdy=j; 
            }
            if(mg[i][j]=='B'){
                zdx=i;
                zdy=j;
            }   
        }
    }
    //cout<<"10";
    pd[qdx][qdy]=1;
    q.push((stm){qdx,qdy,0});
    while(!q.empty()){
        t=q.front();
        q.pop();

        for(int i=0;i<4;i++){
            if(t.x==zdx&&t.y==zdy){
                cout<<t.step-1;
                return 0;
            }
            dx=t.x+xa[i];
            dy=t.y+ya[i];
            if(pd[dx][dy]==1){
                if(sum>t.step)
                    sum=t.step;
                else
                    continue;
            }
            if(mg[dx][dy]!='x'&&dx>=1&&dx<=n&&dy>=1&&dy<=n){
                pd[t.x][t.y]=1;
                q.push((stm){dx,dy,t.step}); 
            } 
            else {
                t.step++;
            }
        }
        sum=t.step;
    }
    cout<<"-1";
    return 0;
}

by makerli @ 2023-06-16 20:33:07

建议用DFS


|