#include<bits/stdc++.h>
using namespace std;
const int maxn=1000;
typedef long long ll;
char dt[maxn][maxn]={};
ll ans=0,ans_dt[maxn][maxn]={},arr2[maxn][maxn]={},x,y,n,m,walk[6][2]={{0,0},{0,1},{1,0},{-1,0},{0,-1}};
struct wz{
ll x,y;
};
queue<wz> Q;
void bfs(ll x,ll y){
wz tmp={x,y};
Q.push(tmp);
while(!Q.empty()){
wz u=Q.front();
ll ux=u.x,uy=u.y;
Q.pop();
for(int i=0;i<5;i++){
ll x=ux+walk[i][0],y=uy+walk[i][1];
if(x<1 or x>n or y<1 or y>n or ans_dt[x][y]==ans_dt[ux][uy] or ans_dt[x][y]==-1){
continue;
}
else{
ans++;
ans_dt[x][y]=-1;
}
wz tmp={x,y};
Q.push(tmp);
}
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>dt[i][j];
if(dt[i][j]=='1'){
ans_dt[i][j]=1;
}
if(dt[i][j]=='0'){
ans_dt[i][j]=0;
}
}
}
memcpy(arr2,ans_dt,sizeof(ans_dt));
for(int i=1;i<=m;i++){
cin>>x>>y;
bfs(x,y);
cout<<ans<<endl;
memcpy(ans_dt,arr2,sizeof(arr2));
ans=0;
}
return 0;
}