#include<bits/stdc++.h>
using namespace std;
int n,m;
struct node{
int x,y;
};
int a[1005][1005],vis[1005][1005],anss[1005][1005];
const int movex[4][2] = {{0,1},{0,-1},{-1,0},{1,0}};
int main(){
scanf("%d%d",&n,&m);
for(int i = 1; i <= n; i++){
string s;
cin >> s;
for(int j = 0; j < n; j++){
a[i][j+1] = s[j]-'0';
}
}
int s[2];
s[0] = 1;
s[1] = 0;
while(m--){
queue<node>q;
queue<node>q2;
int x,y;
scanf("%d%d",&x,&y);
if(anss[x][y]){
printf("%d\n",anss[x][y]);
continue;
}
memset(vis,0,sizeof(vis));
q.push((node){x,y});
vis[x][y] = 1;
int ans = 1;
while(q.size()){
node tmp = q.front();
q.pop();
for(int i = 0;i < 4; i++){
int xx = tmp.x+movex[i][0];
int yy = tmp.y+movex[i][1];
if(xx > n || xx < 1 || yy > n || yy < 1 || vis[xx][yy] || a[xx][yy] != s[a[tmp.x][tmp.y]]){
continue;
}
ans++;
vis[xx][yy] = 1;
q.push((node){xx,yy});
q2.push((node){xx,yy});
}
}
anss[x][y] = ans;
while(q2.size()){
anss[q2.front().x][q2.front().y] = ans;
q2.pop();
}
printf("%d\n",ans);
}
return 0;
}