#include<bits/stdc++.h>
using namespace std;
int n, m, ans[1005][1005], sum;
bool a[1005][1005];
void dfs(int x, int y, bool flag) {
if (x < 1 || x > n || y < 1 || y > n) return;
if (a[x][y] != flag || ans[x][y] != -1) return;
ans[x][y] = 0x3f3f3f3f;
sum++;
dfs(x - 1, y, !flag);
dfs(x, y + 1, !flag);
dfs(x + 1, y, !flag);
dfs(x, y - 1, !flag);
}
void overed() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) if (ans[i][j] == 0x3f3f3f3f) ans[i][j] = sum;
}
sum = 0;
}
int main(){
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
char tmp;
cin >> tmp;
if (tmp == '0') a[i][j] = false;
else a[i][j] = true;
}
}
memset(ans, -1, sizeof ans);
for (int i = 1; i <= m; i++) {
int x, y;
cin >> x >> y;
if (ans[x][y] == -1) {
dfs(x, y, a[x][y]);
overed();
}
cout << ans[x][y] << endl;
}
return 0;
}