https://www.luogu.org/problemnew/show/P1141
题解:不知道为什么只要是连通块就行了
BFS
/*
*@Author: STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
using namespace std;
typedef long long ll;
typedef __int128 lll;
const int N=1000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m,k,x,y;
int a[N][N];
int vis[N][N];
int b[][2]={1,0,0,1,-1,0,0,-1};
string str;
struct node{
int x,y;
}s,f,tmp;
queue<node>q;
int cnt=0;
int ans[N*N];
void bfs(){
s.x=x;
s.y=y;
while(!q.empty())
q.pop();
q.push(s);
//memset(vis,0,sizeof(vis));
vis[x][y]=cnt;
ans[cnt]=1;
while(!q.empty()){
f=q.front();
q.pop();
for(int i=0;i<4;i++){
tmp.x=f.x+b[i][0];
tmp.y=f.y+b[i][1];
if(vis[tmp.x][tmp.y])
continue;
if(0<tmp.x&&tmp.x<=n&&0<tmp.y&&tmp.y<=n&&a[f.x][f.y]!=a[tmp.x][tmp.y]){
ans[cnt]++;
vis[tmp.x][tmp.y]=cnt;
q.push(tmp);
}
}
}
}
int main()
{
#ifdef DEBUG
freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
#endif
//ios::sync_with_stdio(false);
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
cin>>str;
for(int j=1;j<=n;j++){
a[i][j]=str[j-1]-'0';
}
}
while(m--){
scanf("%d%d",&x,&y);
if(vis[x][y]){
printf("%d\n",ans[vis[x][y]]);
continue;
}
cnt++;
bfs();
printf("%d\n",ans[vis[x][y]]);
//cout << ans+1 << endl;
}
//cout << "Hello world!" << endl;
return 0;
}