#include <iostream>
using namespace std;
char s[1002][1002];
int n, m, b[100002][3], f[1002][1002], visit[1002][1002] = {0};
int dfs(int x, int y) {
if (visit[x][y])
return 0;
visit[x][y] = 1;
int cnt = 1;
int nx[4] = {-1, 0, 1, 0};
int ny[4] = {0, 1, 0, -1};
for (int i = 0; i < 4; i++) {
int fx = nx[i] + x;
int fy = ny[i] + y;
if (fx >= 1 && fy >= 1 && fx <= n && fy <= n) {
if (s[x][y] == '0') {
if (s[fx][fy] == '1') {
cnt += dfs(fx, fy);
}
} else {
if (s[fx][fy] == '0') {
cnt += dfs(fx, fy);
}
}
}
}
return cnt;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> (s[i] + 1);
}
for (int i = 1; i <= m; i++) {
cin >> b[i][1] >> b[i][2];
}
for (int i = 1; i <= m; i++) {
int x = b[i][1];
int y = b[i][2];
int cnt = dfs(x, y);
cout << cnt << "\n";
}
return 0;
}