bfs WA两个点求助!!!
查看原帖
bfs WA两个点求助!!!
546706
huahua02811楼主2022/1/24 10:27
#include<bits/stdc++.h>
using namespace std;
const int N = 1010;
int a[N][N];
typedef pair<int, int> PII;
PII q[N*N];
int n,m;
int ct[N],cnt;
int dist[N][N];
int dx[4] = {-1,0,1,0};
int dy[4] = {0,1,0,-1};
void bfs(int sx,int sy)
{
    dist[sx][sy] = cnt;
    int hh = 0,tt = -1;
    q[++tt] = {sx,sy};
    int ans = 1;
    while(hh<=tt)
    {
        auto t = q[hh++];
        // if(dist[t.first][t.second]) continue;
        dist[t.first][t.second] = cnt;
        for(int i = 0;i<4;i++)
        {
            int nx = dx[i]+t.first,ny = dy[i]+t.second;
            if(dist[nx][ny]) continue;
            if(a[nx][ny]==a[t.first][t.second])continue;
            if(nx<=0||ny<=0||nx>n||ny>n) continue;
            ans++;
            dist[nx][ny] = cnt;
            q[++tt] = {nx,ny};
        }
    }
    ct[cnt] = ans;
}
int main()
{
    memset(dist,0,sizeof dist);
    cin>>n>>m;
    for(int i = 1;i<=n;i++)
    {
        for(int j = 1;j<=n;j++)
        {
            char c;
            cin>>c;
            a[i][j] = c-'0';
        }
    }
    cnt = 0;
    while (m -- ){
        int x,y;
        cin>>x>>y;
        if(dist[x][y])
            cout<<ct[dist[x][y]]<<endl;
        else
        {        
            cnt++;
            bfs(x,y);
            cout<<ct[dist[x][y]]<<endl;
        }
    }
    return 0;
}
2022/1/24 10:27
加载中...