Carl_T_C @ 2024-11-13 13:52:14
#include<iostream>
#include<queue>
using namespace std;
bool s[1001][1001];
int g[1001][1001]={0};
int X[5]={0,1,0,-1,0};
int Y[5]={0,0,1,0,-1};
struct node{
int x,y;
};
queue<node>q;
int main(){
ios_base::sync_with_stdio(0);
int n,m;
char d;
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>d;
if(d=='0'){
s[i][j]=0;
}else{
s[i][j]=1;
}
}
}
for(int a=1;a<=n;a++){
for(int b=1;b<=n;b++){
node f;
f.x=a,f.y=b;
q.push(f);
bool vis[1001][1001]={0};
vis[a][b]=1;
int ans=1;
while(!q.empty()){
node mid,now;
mid=q.front();
q.pop();
for(int j=1;j<=4;j++){
now.x=mid.x+X[j];
now.y=mid.y+Y[j];
if(now.x&&now.y&&now.x<=n&&now.y<=n&&!vis[now.x][now.y]&&s[mid.x][mid.y]!=s[now.x][now.y]){
// cout<<a<<" "<<b<<" "<<now.x<<" "<<now.y<<endl;
ans++;
vis[now.x][now.y]=1;
q.push(now);
}
}
}
g[a][b]=ans;
while(!q.empty())q.pop();
}
}
for(int i=1;i<=m;i++){
int a,b;
cin>>a>>b;
cout<<g[a][b]<<endl;
}
return 0;
}
by mmh08100566 @ 2024-11-13 14:02:10
@Carl_T_C 做法不够优,请使用时间复杂度更低的算法
by Carl_T_C @ 2024-11-13 14:02:43
ok @mmh08100566
by hermione_wqx @ 2024-11-13 17:58:16
@Carl_T_C 学长互关