#include<bits/stdc++.h>
using namespace std;
int v[1001][1001],t[1000001][2], a[1001][1001];
int n, m, c, sx, sy;
int dx[5] = {0, 1, -1, 0, 0}, dy[5] = {0, 0, 0, 1, -1};
char x;
int o, p;
void judge(int x, int y){
if(x < 1 || x > n || y < 1 || y > n){
return;//出界
}
if(v[x][y]){
return;
}
c++;
t[c][0] = x;
t[c][1] = y;
v[x][y] = 1;
for(int i = 1; i <= 4; i++){
if(a[x][y] != a[x+dx[i]][y+dy[i]]){
judge(x + dx[i], y + dy[i]);
}
}
}
int main(){
memset(v, 0, sizeof(v));
cin >> n >> m;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
cin >> x;
a[i][j] = x - '0';
}
}
for(int i = 1; i <= m; i++){
cin >> o >> p;
c = 0;
if(v[o][p] > 0){
cout << v[o][p] << endl;
continue;
}
judge(o, p);
for(int i = 1; i <= c; i++){
v[t[i][0]][t[i][1]] = c;
}
cout << c << endl;
}
return 0;
}