求助,80分

P1746 离开中山路

mmy129 @ 2022-08-16 16:05:17

#include<bits/stdc++.h>
using namespace std;
int n;
struct pos{
    int x,y;
}a,b;
queue<pos> q;
int mp[1005][1005],x2,y2,x3,y3;
int dx[4]={1,-1,0,0},dy[4]={0,0,1,-1}; 
bool vis[1005][1005];
int tot[1005][1005];
int main(){
    cin>>n;
    string s;
    for(int i=1;i<=n;i++){
        cin>>s;
        for(int j=0;j<3;j++){
                mp[i][j]=s[j]-'0';
        } 
    }
    cin>>x2>>y2>>x3>>y3;
    a.x=x2,a.y=y2;
    q.push(a);
    vis[x2][y2]=1;
    while(!q.empty()){
        a=q.front();
        q.pop();
        cout<<a.x<<" "<<a.y<<endl;
        if(a.x==x3&&a.y==y3){
            cout<<tot[a.x][a.y];
            return 0;
        }
        for(int i=0;i<4;i++){
            int px=dx[i]+a.x;
            int py=dy[i]+a.y;
            if(px>=1&&py>=1&&py<=n&&px<=n&&vis[px][py]==0&&mp[px][py]!=1){
                tot[px][py]=tot[a.x][a.y]+1;
                vis[px][py]=1;
                b.x=px,b.y=py;
                q.push(b);
            }
        }
    }
    return 0;
}

by s_c_lmlm_L @ 2022-08-16 16:19:16

@mmy129 这不0分??


by _Glassy_Sky_ @ 2022-08-16 16:32:10

#include<iostream>
#include<queue>
using namespace std;
struct Pos
{
    int x,y;
};
queue <Pos> q;
int n,x,y,tx,ty,dis[1001][1001],s_a,s_b,t_a,t_b;
const int dx[]={1,-1,0,0};
const int dy[]={0,0,1,-1};
char mp[1001][1001];
bool vis[1001][1001];
int bfs(int sx,int sy)
{
    q.push((Pos){sx,sy});
    vis[sx][sy]=true;
    while(!q.empty())
    {
        x=q.front().x;
        y=q.front().y;
        q.pop();
        if(x==t_a&&y==t_b) return dis[x][y];
        for(int i=0;i<4;i++)
        {
            tx=x+dx[i];
            ty=y+dy[i];
            if(tx<=0||tx>n||ty<=0||ty>n) continue;
            if(mp[tx][ty]=='1'||vis[tx][ty]==true) continue;
            dis[tx][ty]=dis[x][y]+1;
            vis[tx][ty]=true;
            q.push((Pos){tx,ty});
        }
    }
    return -1;
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            cin>>mp[i][j];
    cin>>s_a>>s_b>>t_a>>t_b;
    cout<<bfs(s_a,s_b);
    return 0;

}

|