计算连通块数量&大小代码
CRH380AatNC · · 算法·理论
#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;
}