#include <bits/stdc++.h>
using namespace std;
int s[1010][1010], cnt = 0, ans[1010][1010], n, m;
int nextstep[6][3] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
void dfs(int x, int y){
if (x > n || x < 1 || y > n || y < 1) return;
if (ans[x][y] > -1) return;
cnt++;
ans[x][y] = 0;
for (int i = 0; i < 4; i++){
if (s[x + nextstep[i][0]][y + nextstep[i][1]] != s[x][y]) dfs(x + nextstep[i][0], y + nextstep[i][1]);
}
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
char str[100005];
cin >> str;
for(int j = 1; j <= n; j++){
s[i][j] = str[j - 1] - 48;
}
}
for(int i = 1; i <= m; i++){
memset(ans, -1, sizeof(ans));
int a, b;
cnt = 0;
cin >> a >> b;
dfs(a, b);
cout << cnt << endl;
}
}