#include<bits/stdc++.h>
using namespace std;
int n,m,ans,a,b;
int mx[]={0,0,1,-1},my[]={1,-1,0,0},bn[1010][1010];
char c[1010][1010];
struct node
{
int x,y;
};
void clear(queue<int>&q)
{
queue<int>empty;
swap(empty,q);
}
queue<node>Q;
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cin>>c[i][j];
for(int i=1;i<=m;i++)
{
ans=1;
cin>>a>>b;
Q.push((node){a,b});
bn[a][b]=1;
while(!Q.empty())
{
node temp=Q.front();
Q.pop();
for(int i=0;i<4;i++)
{
int tx=temp.x+mx[i],ty=temp.y+my[i];
if(tx>0&&tx<=n&&ty>0&&ty<=n&&bn[tx][ty]==0)
{
if(c[temp.x][temp.y]=='0'&&c[tx][ty]=='1')
{
Q.push((node){tx,ty});
bn[tx][ty]=1;
ans++;
}
if(c[temp.x][temp.y]=='1'&&c[tx][ty]=='0')
{
Q.push((node){tx,ty});
bn[tx][ty]=1;
ans++;
}
}
}
}
cout<<ans<<endl;
while(!Q.empty())Q.pop();
memset(bn,0,sizeof(bn));
}
return 0;
}
T了2、9、10