跳到正文

算法·理论

计算连通块数量&大小代码

CRH380AatNC约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年7月28日
收录
2025年12月12日
更新
2026年11月20日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
const int N=1500;
char c[N][N]; 
int X,Y,n,m,k,s,d,f[N][N],a[N*N];
struct G{
    int x;
    int y;
}q[N*N];
int dx[4]={0,0,-1,1};
int dy[4]={1,-1,0,0};
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>c[i][j];
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(!f[i][j]){
                int h=1,t=1;
                q[h].x=i;q[h].y=j;
                f[i][j]=++d;
                s=1;
                while(h<=t){
                    for(int k=0;k<4;k++){
                        int fx=q[h].x+dx[k],fy=q[h].y+dy[k];
                        if(fx>=1&&fx<=n&&fy>=1&&fy<=n&&c[fx][fy]!=c[q[h].x][q[h].y]&&!f[fx][fy]){
                            t++;s++;
                            f[fx][fy]=d;
                            q[t].x=fx,q[t].y=fy;
                        }
                    }
                    h++;
                }
                a[d]=s;
            }
        }
    }
    for(int i=1;i<=m;i++){
        cin>>X>>Y;
        cout<<a[f[X][Y]]<<endl;
    }
    return 0;
}
原文