by0113 @ 2024-10-14 13:00:25
#include<bits/stdc++.h>
using namespace std;
int mapp[10000][10010];
int qx[10010],qy[10010];
int dx[16]={-4,-3,-2,-1,1,2,3,4,0,0,0,0,0,0,0,0};
int dy[16]={0,0,0,0,0,0,0,0,-4,-3,-2,-1,1,2,3,4};
int vis[10010][10010];
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)
{
string s;
cin>>s;
for(int j=0;j<s.size();j++)
{
mapp[i][j+1]=s[j]-48;
}
}
while(m--)
{
int stx,sty,ans=0;
memset(qx,0,sizeof(qx));
memset(qy,0,sizeof(qy));
memset(vis,0,sizeof(vis));
cin>>stx>>sty;
int front=-1,tail=0;
qx[0]=stx,qy[0]=sty;
while(front<tail)
{
front++;
int tx=qx[front],ty=qy[front];
for(int i=0;i<=15;i++)
{
int rx=tx+dx[i];
int ry=ty+dy[i];
if(rx>=1&&rx<=n&&ry>=1&&ry<=n&&vis[rx][ry]==0&&mapp[rx][ry]==!(mapp[tx][ty]))
{
vis[rx][ry]=1;
ans++;
tail++;
qx[tail]=rx;
qy[tail]=ry;
}
}
}
cout<<ans<<endl;
}
}