__owen__ @ 2025-01-08 19:59:47
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
int n,ans,m,sx,sy,tx,ty,flag;
typedef pair<int,int> PII;
const int N = 1100;
char g[N][N];
int vis[N][N];
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
int bfs(int x,int y){
queue<PII> q;
q.push({x,y});
vis[x][y] = 1;
while(q.size()){
auto cur = q.front();
q.pop();
int x=cur.first,y=cur.second;
for(int i=0;i<4;i++){
int nx=x+dx[i],ny=y+dy[i];
if(nx>=0&&nx<n&&ny>=0&&ny<n&&!vis[nx][ny]&&g[nx][ny] != g[x][y]){
ans++;
q.push({nx,ny});
vis[nx][ny] = 1;
}
}
}
}
int main()
{
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>g[i][j];
}
}
while(m--){
int i,j;cin>>i>>j;
i--,j--;
ans = 1;
memset(vis,0,sizeof vis);
bfs(i,j);
cout << ans << endl;
}
return 0;
}