#include<bits/stdc++.h>
#define int long long
#define QWQ cin.tie(0)->sync_with_stdio(false);
using namespace std;
const int maxn = 11111;
const int dx[4] = {1, -1, 0, 0};
const int dy[4] = {0, 0, -1, 1};
char g[maxn][maxn];
bool vis[maxn][maxn];
int st[maxn][2], ans[maxn][maxn];
int n, m, i, j, now;
void dfs(int x, int y){
++now;
st[now][0] = x, st[now][1] = y;
for(int i = 0; i < 4; i++){
int xx = dx[i] + x;
int yy = dy[i] + y;
if(xx >= 1 and yy >= 1 and xx <= n and yy <= n and (g[x][y] != g[xx][yy]) and !vis[xx][yy]){
vis[xx][yy] = true;
dfs(xx, yy);
}
}
}
signed main(){
QWQ
cin >> n >> m;
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
cin >> g[i][j];
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++){
if(!vis[i][j]){
now = 0;
vis[i][j] = true;
dfs(i, j);
for(int i = 1; i <= now; i++){
ans[st[i][0]][st[i][1]] = now;
}
}
}
while(m--){
cin >> i >> j;
cout << ans[i][j] << endl;
}
return 0;
}