#include<bits/stdc++.h>
using namespace std;
queue<int> x,y;
int tx[4]={0,1,0,-1};
int ty[4]={1,0,-1,0};
char s[1010];
int a[1010][1010],b[1010][1010],sum[101000], n , m ,k;
int bfs()
{
while(x.size())
{
b[x.front()][y.front()]=k;
for(int i=0;i<=3;i++)
{
int fx=x.front()+tx[i];
int fy=y.front()+ty[i];
if(fx>0&&fy>0&&fx<=n&&fy<=n&&a[x.front()][y.front()]!=a[fx][fy]&&b[fx][fy]==0)
{
x.push(fx);
y.push(fy);
sum[k]++;
}
}
x.pop();
y.pop();
}
return 0;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>s;
for(int j=0;j<n;j++)
{
a[i][j+1]=s[j]-'0';
}
}
for(int j=1;j<=m;j++)
{
int x12,y12;
cin>>x12>>y12;
if(b[x12][y12])
{
}
else
{
k++;
x.push(x12);
y.push(y12);
bfs();
}
cout<<sum[b[x12][y12]]<<endl;
}
return 0;
}