#include <bits/stdc++.h>
using namespace std;
const int N=1e3+5;
int n,m,d=0,a[1000003],ans,dx[]={0,1,-1,0,0},dy[]={0,0,0,1,-1},flag[N][N];
char map2[N][N];
struct po{
int x;
int y;
po(int xx,int yy)
{
x=xx;
y=yy;
}
};
queue<po>q;
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)scanf("%s",map2[i]+1);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(!flag[i][j]){
d++;
flag[i][j]=d;
ans=1;
po c(i,j);q.push(c);
while(!q.empty()){
po b=q.front();q.pop();
for(int i=1;i<=4;i++){
int xx=b.x+dx[i];
int yy=b.y+dy[i];
if(!flag[xx][yy]&&xx>=1&&xx<=n&&yy>=1&&yy<=n&&map2[xx][yy]!=map2[b.x][b.y])
{
flag[xx][yy]=d;
po e(xx,yy);
q.push(e);
ans++;
}
}
}
a[d]=ans;
}
}
}
while(m--){
int uu,ii;scanf("%d%d",&uu,&ii);
printf("%d\n",a[flag[uu][ii]]);
}
return 0;
}