#include <bits/stdc++.h>
using namespace std;
int n, m, ans;
bool a[1005][1005], vis[1005][1005];
int jy[1005][1005];
int py[4][2] = {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
struct node {
int x, y;
};
queue<node> s;
int bfs(int x, int y) {
queue<node> q;
s.push((node) {
x, y
});
q.push((node) {
x, y
});
vis[x][y] = 1;
while (!q.empty()) {
int tx = q.front().x;
int ty = q.front().y;
q.pop();
++ans;
for (int i = 0; i < 4; ++i) {
int ttx = tx + py[i][0];
int tty = ty + py[i][1];
if (ttx <= 0 || tty <= 0 || ttx > n || tty > n || vis[ttx][tty]) {
continue;
} else if (!(a[tx][ty] ^ a[ttx][tty])) {
continue;
}
vis[ttx][tty] = 1;
q.push((node) {
ttx, tty
});
s.push((node) {
ttx, tty
});
}
}
return ans;
}
int main() {
ios::sync_with_stdio(0);
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
char t;
cin >> t;
a[i][j] = t - '0';
}
}
while (m--) {
int tx, ty;
cin >> tx >> ty;
if (jy[tx][ty]) {
cout << jy[tx][ty] << endl;
continue;
} else {
cout << bfs(tx, ty) << endl;
memset(vis, 0, sizeof(vis));
while (!s.empty()) {
jy[s.front().x][s.front().y] = ans;
s.pop();
}
ans = 0;
}
}
return 0;
}