#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
struct node{
int x,y,c;
};
int ftion(int h)
{
if(h==1)
{
return 0;
}
if(h==0)
{
return 1;
}
}
int map[1005][1005],n,m,x1,y1,flag[1005][1005];
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
char s[1005];
int bfs(int xx,int yy,int cc)
{
queue<node>q;
memset(flag,0,sizeof(flag));
flag[xx][yy]=1;
int sum=1;
node tmp;
tmp.x=xx;
tmp.y=yy;
tmp.c=cc;
q.push(tmp);
while(!q.empty())
{
node f;
f=q.front();q.pop();
for(int i=0;i<4;i++)
{
int nx=f.x+dx[i],ny=f.y+dy[i];
if(map[nx][ny]!=f.c && !flag[nx][ny] && nx>0 && ny>0 && nx<=n && ny<=n)
{
node t;
t.x=nx;
t.y=ny;
t.c=ftion(f.c);
sum++;
flag[nx][ny]=1;
q.push(t);
}
}
}
return sum;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%s",s+1);
for(int j=1;j<=n;j++)
{
map[i][j]=int(s[j]-'0');
}
}
for(int i=1;i<=m;i++)
{
scanf("%d%d",&x1,&y1);
printf("%d\n",bfs(x1,y1,map[x1][y1]));
}
return 0;
}