#include<bits/stdc++.h>
using namespace std;
char s[1010][1010];
int mp[1010][1010],vis[1010][1010],f[100001][2];
int n,m,ans;
int xx,yy;
inline int read()
{
int s=0,f=1;
char ch=getchar();
while(ch>'9'||ch<'0')
{
if(ch=='-')
f*=-1;
ch=getchar();
}
while(ch<='9'&&ch>='0')
{
s=s*10+ch-'0';
ch=getchar();
}
return s*f;
}
inline void write(int x){
if(x<0){
putchar('-');
x=-x;
}
if(x>9)
write(x/10);
putchar(x%10+'0');
}
void bfs(int x,int y)
{
if((x>n||x<1)||(y>n||y<1))
return ;
if(!vis[x][y])
ans++,vis[x][y]=1;
if(!vis[x+1][y]&&(mp[x+1][y]!=mp[x][y])) bfs(x+1,y);
if(!vis[x-1][y]&&(mp[x-1][y]!=mp[x][y])) bfs(x-1,y);
if(!vis[x][y+1]&&(mp[x][y+1]!=mp[x][y])) bfs(x,y+1);
if(!vis[x][y-1]&&(mp[x][y-1]!=mp[x][y])) bfs(x,y-1);
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
cin>>s[i];
for(int i=1;i<=n;i++)//这里是把地图从一开始表示
{
for(int j=0;j<n;j++)
mp[i][j+1]=s[i][j];
}
for(int i=1;i<=m;i++)
f[i][0]=read(),f[i][1]=read();
for(int j=1;j<=m;j++)
{
for(int i=1;i<=n;i++)
for(int l=1;l<=n;l++)
vis[i][l]=0;
ans=0;
int x=f[j][0];
int y=f[j][1];
bfs(x,y);
write(ans);
puts("");
}
system("pause");
return 0;
}