wuyuxuan20090114 @ 2024-09-13 21:50:22
#include<iostream>
#include<cstring>
using namespace std;
char a[1001][1001];
int f[1001][1001],n,m,c[1001][1001],ans,fa[1000001];
short x1[4]={0,1,0,-1};
short y1[4]={1,0,-1,0};
bool vis[1001][1001];
void dfs(int x,int y,int b){
for(int i=0;i<4;i++){
int dx=x+x1[i];
int dy=y+y1[i];
if(vis[dx][dy]==0&&f[dx][dy]!=f[x][y]&&dx>=1&&dx<=n&&dy>=1&&dy<=n){
vis[dx][dy]=1;
c[x][y]=b;
dfs(dx,dy,b);
//vis[dx][dy]=0;
}
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>a[i][j];
f[i][j]=a[i][j]-'0';
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
memset(vis,0,sizeof(vis));
if(c[i][j]==0){
ans++;
dfs(i,j,ans);
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
fa[c[i][j]]++;
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
c[i][j]=fa[c[i][j]];
}
}
for(int i=1;i<=m;i++){
int x,y;
cin>>x>>y;
cout<<c[x][y]<<endl;
}
return 0;
}
一下数据人都傻了,这么大....
深搜连通块,再用c[i][j]数组存每个点能到的点个数,复杂度O(n^3)