#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> PA;
int n, m;
int a[1005][1005];
int bl[1005][1005];
int d[1005][1005];
int ans[1005];
int dx[4] = { -1,0,1,0 };
int dy[4] = { 0,-1,0,1 };
int bfs(int x,int y,int g) {
int cout = 1;
queue<PA> q;
q.push({x,y});
bl[x][y] = 1;
while (!q.empty()) {
auto t = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int fx = t.first + dx[i];
int fy = t.second + dy[i];
if (fx >= 1 && fx <= n && fy >= 1 && fy <= n && a[fx][fy] != a[t.first][t.second] && !bl[fx][fy]) {
bl[fx][fy] = 1;
q.push({ fx,fy });
d[fx][fy] = g;
cout++;
}
}
}
return cout;
}
int main() {
ios::sync_with_stdio(0);
memset(bl, 0, sizeof(bl));
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
char c[1005];
scanf("%s", c);
for (int j = 1; j <= n; j++) {
a[i][j] = c[j - 1] - '0';
}
}
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d%d", &x, &y);
if (!bl[x][y]) {
d[x][y] = i;
ans[i] = bfs(x, y, i);
cout << ans[i] << endl;
}
else {
cout << ans[d[x][y]] << endl;
}
}
return 0;
}