#include <bits/stdc++.h>
using namespace std;
const int N=1010;
int n,m,x,y,L=0,R=-1,px[4]={-1,0,1,0},py[4]={0,1,0,-1},len,sum;
char M[N][N];
bool V[N][N];
pair <int,int> Q[N*N];
inline bool hf(int a,int b)
{
return a>0&&b>0&&a<=n&&b<=n&&(!V[a][b]);
}
inline void my_pop()
{
L++;
}
inline void my_push(int a,int b)
{
if(hf(a,b))
{
R++;
Q[R].first=a;
Q[R].second=b;
V[a][b]=true;
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
cin>>M[i]+1;
for(int i=1;i<=m;i++)
{
L=0;
R=-1;
len=0;
cin>>x>>y;
my_push(x,y);
while(L<=R)
{
int xx=Q[L].first;
int yy=Q[L].second;
for(int j=0;j<4;j++)
{
int tx=xx+px[j];
int ty=yy+py[j];
if(M[tx][ty]!=M[xx][yy])
my_push(tx,ty);
}
my_pop();
}
cout<<R+1<<endl;
for(register int j=0;j<=R;j++)
V[Q[j].first][Q[j].second]=false;
}
return 0;
}