#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
int n,m;
bool vis[10005][10005];
string mp[10005];
int vir[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int color[10005][10005];
int res[10005];
int p=0;
int BFS(int xx,int yy){
int ans=0;
queue<int> R;
queue<int> L;
R.push(xx);
L.push(yy);
vis[xx][yy]=true;
while(!R.empty()){
int x = R.front();
int y = L.front();
color[x][y]=p;
for(int i=0;i<4;i++){
int tx = x+vir[i][0];
int ty = y+vir[i][1];
if(tx<0||tx>=n||ty<0||ty>=n)continue;
if(mp[x][y]=='0'){
if(mp[tx][ty]=='1'&&!vis[tx][ty]){
vis[tx][ty]=true;
R.push(tx),L.push(ty);
}
}else{
if(mp[tx][ty]=='0'&&!vis[tx][ty]){
vis[tx][ty]=true;
R.push(tx),L.push(ty);
}
}
}
ans++;
R.pop();
L.pop();
}
return ans;
}
int main(){
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++){
cin>>mp[i];
}
while(m--){
int x,y;
scanf("%d %d",&x,&y);
if(color[x-1][y-1]>0){
printf("%d\n",res[color[x-1][y-1]]);
}else{
p++;
res[p]=BFS(x-1,y-1);
printf("%d\n",res[p]);
}
}
return 0;
}