10pts求助!

P1746 离开中山路

duminghao123 @ 2024-08-10 16:59:09

开O2MLE 不开TLE 总是#2AC


#include<bits/stdc++.h>
using namespace std;
int n,x11,y11,x22,y22,p[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
bool a[1001][1001],b[1001][1001];
char a1;
struct pos{
    int x,y,tms;
}k;
queue<pos> q;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>a1;
            a[i][j]=a1-48;
            b[i][j]=a[i][j];
        }
    }
    cin>>x11>>y11>>x22>>y22;
    k.x=x11,k.y=y11,k.tms=0;
    q.push(k);
    while(!q.empty()){
        for(int i=0;i<4;i++){
            if(b[q.front().x+p[i][0]][q.front().y+p[i][1]]==0&&q.front().x+p[i][0]>0&&q.front().x+p[i][0]<=n&&q.front().y+p[i][1]>0&&q.front().y+p[i][1]<=n){
                k.x=q.front().x+p[i][0];
                k.y=q.front().y+p[i][1];
                k.tms=q.front().tms+1;
                q.push(k);
                b[q.front().x][q.front().y]=1;
            }
        }
        if(q.front().x==x22&&q.front().y==y22) {
            cout<<q.front().tms;
            return 0;
        }
        q.pop();
    }
    cout<<-1;
    return 0;
}

by haimingbei @ 2024-08-10 17:02:33

@duminghao123 看看我的(易懂)


using namespace std;
int ans=0,n,x2,y2,x3,y3,aa[1010][1010];
bool bb[1010][1010];
int px[5]={0,-1,0,1,0};
int py[5]={0,0,1,0,-1};
struct ai{
    int x,y;
};
queue <ai> q;
void bfs(int x,int y){
    int u,v;
    bb[x][y]=1;
    ai a;
    a.x=x,a.y=y;
    q.push(a);
    int x2,y2;
    while(!q.empty()){
        x2=q.front().x,y2=q.front().y;
        q.pop();
        for(int i=1;i<=4;i++){
            int u=x2+px[i],v=y2+py[i];
            if(u>=1 && u<=n && v>=1 && v<=n && bb[u][v]==0){
                aa[u][v]=aa[x2][y2]+1;
                bb[u][v]=1;
                ai b;
                b.x=u,b.y=v;
                q.push(b);
            }
        }
    }
}
int main(){
    cin>>n;
    char c;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>c;
            if(c=='1'){
                aa[i][j]=-1;
                bb[i][j]=1;
            }
        }
    }
    cin>>x2>>y2>>x3>>y3;
    bfs(x2,y2);
    cout<<aa[x3][y3];
    return 0;
}```

by duminghao123 @ 2024-08-10 17:05:47

已解决,非常感谢!


|