注意看#2 求优化一下,不用O2也能过
#include<bits/stdc++.h>
using namespace std;
char g[1010][1010];
bool st[1010][1010];
int n,m,deep;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
int dist[1010][1010];
int res[505000];
bool check(int x,int y){
return x>=1&&x<=n&&y>=1&&y<=n;
}
void bfs(int _x,int _y){
queue<pair<int,int>> q;
q.push({_x,_y});
int sum=1;
deep++;
memset(st,false,sizeof st);
st[_x][_y]=true;
while(q.size()){
auto t=q.front();
q.pop();
for(int i=0;i<4;i++){
int x=t.first+dx[i],y=t.second+dy[i];
if(check(x,y)&&!dist[x][y]&&!st[x][y]&&g[x][y]==1-g[t.first][t.second]){
st[x][y]=true;
sum++;
dist[x][y]=deep;
q.push({x,y});
}
}
}
res[deep]=sum;
return ;
}
int main(){
scanf("%d%d",&n,&m);
string s;
for(int i=1;i<=n;i++){
cin>>s;
for(int j=1;j<=n;j++)
g[i][j]=s[j-1]-'0';
}
// for(int i=1;i<=n;i++){
// for(int j=1;j<=n;j++)
// if(!dist[i][j]){
// bfs(i,j);
// dist[i][j]=deep;
// }
// }
//res[0]=1;
while(m--){
int i,j;
scanf("%d%d",&i,&j);
if(!dist[i][j]){
bfs(i,j);
dist[i][j]=deep;
}
printf("%d\n",res[dist[i][j]]);
}
}