#include<bits/stdc++.h>
using namespace std;
char a[1005][1005];
int n,m,x,y;
bool vis[1005][1005];
short dx[]=
{1,0,-1,0},
dy[]=
{0,-1,0,1};
int bfs(int x,int y);
int main(){
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
fread(a[i],1,n,stdin);
for(int i=1;i<=m;i++){
memset(vis,0,sizeof(vis));
scanf("%d%d",&x,&y);
printf("%d\n",bfs(x,y));
}
return 0;
}
int bfs(int x,int y){
int cnt=1;
queue<pair<int,int> >q;
q.push(make_pair(x,y));
vis[x][y]=1;
while(q.size()){
int xx=q.front().first;
int yy=q.front().second;
q.pop();
for(int i=0;i<4;i++){
int xxx=xx+dx[i];
int yyy=yy+dy[i];
if(
xxx>=1 and xxx<=n and
yyy>=1 and yyy<=n and
(not vis[xxx][yyy])and
a[xxx][yyy]!=a[xx][yy]
){
q.push(make_pair(xxx,yyy));
cnt++;
vis[xxx][yyy]=1;
}
}
}
return cnt;
}
//也改了很久了