#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
int n, m;
int b1[4] = {0, 1, -1, 0};
int b2[4] = {1, 0, 0, -1};
char a[MAXN][MAXN];
bool b[MAXN][MAXN];
struct f {
int x, y;
};
queue<f> q;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >> a[i][j];
}
}
while (m--) {
int kx, ky;
cin >> kx >> ky;
int ans = 0;
int sx = kx - 1;
int sy = ky - 1;
memset(b, 0, sizeof(bool) * MAXN * MAXN);
while (!q.empty()) q.pop();
b[sx][sy] = true;
q.push({sx, sy});
ans = 1;
while (!q.empty()) {
f f1 = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
int nx = f1.x + b1[i];
int ny = f1.y + b2[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < n && !b[nx][ny]) {
if ((a[f1.x][f1.y] == '0' && a[nx][ny] == '1') ||
(a[f1.x][f1.y] == '1' && a[nx][ny] == '0')) {
b[nx][ny] = true;
q.push({nx, ny});
ans++;
}
}
}
}
cout << ans << "\n";
}
return 0;
}