#include<bits/stdc++.h>
using namespace std;
const int N=1000+10;
int n,m,D[N][N],vis[10005][10005],ans;
char my_map;
int X[10]={0,1,-1,0,0};
int Y[10]={0,0,0,1,-1};
struct node{
int xxx;
int yyy;
};
void bfs(int a,int b)
{
queue<node>q;
vis[a][b]=1;
q.push({a,b});
while(!q.empty()){
node now=q.front();
q.pop();
for(int i=1;i<=4;i++){
int xx=now.xxx+X[i];
int yy=now.yyy+Y[i];
if(xx<=n || yy<=n || xx>0 || yy>0|| vis[xx][yy]==0){
if(D[now.xxx][now.yyy]==1){
if(D[xx][yy]==1 ) continue;
ans++;
q.push({xx,yy});
}
if(D[now.xxx][now.yyy]==0){
if(D[xx][yy]==0) continue;
ans++;
q.push({xx,yy});
}
}
}
}
ans=0;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>my_map;
if(my_map=='1')D[i][j]=1;
if(my_map=='0')D[i][j]=0;
}
}
for(int i=1;i<=m;i++){
int x,y;
cin>>x>>y;
bfs(x,y);
memset(vis,0,sizeof(vis));
}
return 0;
}