#include <bits/stdc++.h>
using namespace std;
const int inf = 1001;
char a[inf][inf], b[inf][inf];
bool v[inf][inf];
int n, m, ans,
fx[5] = {0, -1, 1, 0, 0},
fy[5] = {0, 0, 0, -1, 1};
void dfs(int x, int y){
v[x][y] = true, ans++;
for(int i=1; i<=4; i++){
int xx = x + fx[i],
yy = y + fy[i];
if(
xx >= 1 && xx <= n &&
yy >= 1 && yy <= n &&
b[xx][yy] != b[x][y] &&
!v[xx][yy]
) dfs(xx, yy);
}
}
int main(){
ios :: sync_with_stdio(false);
cin >> n >> m;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
cin >> a[i][j];
}
}
while(m--){
memcpy(b, a, sizeof(a));
memset(v, 0, sizeof(v));
ans = 0;
int x, y;
cin >> x >> y;
dfs(x, y);
cout << ans << endl;
}
return 0;
}