#include <bits/stdc++.h>
using namespace std;
const int N = 1e3+5;
char mp[N][N];
bool visit[N][N];
int n, m;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
bool check(int x, int y){
return (x >= 0 && x < n && y >= 0 && y < n);
}
int bfs(int x, int y) {
int ans = 1;
visit[x][y] = 1;
queue<pair<int,int>> que;
que.push({x, y});
while(!que.empty()){
x = que.front().first;
y = que.front().second;
que.pop();
for(int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(check(nx,ny) && !visit[nx][ny] && mp[x][y] != mp[nx][ny]) {
ans++;
visit[nx][ny] = 1;
que.push({nx,ny});
}
}
}
return ans;
}
int main() {
scanf("%d %d", &n, &m);
for(int i = 0; i < n; i++) {
scanf("%s", &mp[i]);
}
int x, y;
for(int i = 1; i <= m; i++) {
scanf("%d %d", &x, &y);
memset(visit, 0, sizeof(visit));
printf("%d\n", bfs(x, y));
}
return 0;
}