#include<bits/stdc++.h>
using namespace std;
int n, m, id;
int mapa[1005][1005];
int vis[1005][1005];
int sx, sy;
int ans[10005];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
struct node {
int x, y;
};
void bfs(int x, int y) {
queue<node> q;
q.push({x, y});
vis[x][y] = 1;
while (!q.empty()) {
node now = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int xx = now.x + dx[i];
int yy = now.y + dy[i];
if (xx < 1 || xx > n || yy < 1 || yy > n || vis[xx][yy] == 1 || mapa[now.x][now.y] == mapa[xx][yy])continue;
ans[id]++;
vis[xx][yy] = id;
q.push({xx, yy});
}
}
}
signed main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
char c;
cin >> c;
mapa[i][j] = c - '0';
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (vis[i][j] == 0) {
id++;
bfs(i, j);
}
}
}
while (m--) {
cin >> sx >> sy;
cout << ans[vis[sx][sy]] + 1 << endl;
}
return 0;
}