0分求调
查看原帖
0分求调
1615210
wjhits楼主2024/12/15 11:52

#include #include<string.h> using namespace std; #include #define N 510 int dist[N][N]; int n,m,a,b; queue<pair<int,int>> q; int dx[]={-1,0,1,0}; int dy[]={0,1,0,-1}; void bfs() { while(q.size()) { auto k=q.front(); q.pop(); for(int i=0;i<4;i++) { int a=k.first+dx[i]; int b=k.second+dy[i]; if(a<1 || b<1 || a>n || b>m) continue; if(dist[a][b]>0) continue; dist[a][b]=dist[k.first][k.second]+1; q.push({a,b});

}

} } int main() { memset(dist,-1,sizeof(dist)); cin>>n>>m>>a>>b; while(a--) { int x1,y1; cin>>x1>>y1; q.push({x1,y1}); dist[x1][y1]=0; } bfs(); while(b--) { int x2,y2; cin>>x2>>y2; cout<<dist[x2][y2]<<endl; } return 0; }

#include<iostream>
#include<string.h>
using namespace std;
#include<queue>
#define N 510
int dist[N][N];
int n,m,a,b;
queue<pair<int,int>> q;
int dx[]={-1,0,1,0};
int dy[]={0,1,0,-1};
void bfs()
{   while(q.size())
  {
    auto k=q.front();
    q.pop();
    for(int i=0;i<4;i++)
    {
        int a=k.first+dx[i];
        int b=k.second+dy[i];
        if(a<1 || b<1 || a>n || b>m)  continue;
        if(dist[a][b]>0)  continue;
        dist[a][b]=dist[k.first][k.second]+1;
        q.push({a,b});
         
    }
  }
}
int main()
{   memset(dist,-1,sizeof(dist));
    cin>>n>>m>>a>>b;
    while(a--)
    {
        int x1,y1;
        cin>>x1>>y1;
        q.push({x1,y1});
        dist[x1][y1]=0;
    }
    bfs();
    while(b--)
    {
        int x2,y2;
        cin>>x2>>y2;
        cout<<dist[x2][y2]<<endl;
    }
    return 0;
}
2024/12/15 11:52
加载中...