#include <iostream>
#include <bits/stdc++.h>
#define MAXN 100005
using namespace std;
struct TNode
{
int x;
int y;
};
char mp[1005][1005];
int book[1005][1005];
int step[1005][1005];
int save[1000001][3];
int dx[] = {1,0,-1,0},dy[] = {0,1,0,-1};
void vInput();
void vGetBfs(int x,int y);
int ans;
int n,m;
int main()
{
cin>>n>>m;
vInput();
for(int i=1;i<=m;i++)
{
int sx,sy;
cin>>sx>>sy;
ans = 1;
if(book[sx][sy]==0)
{
vGetBfs(sx,sy);
cout<<step[sx][sy]<<endl;
}
else
{
cout<<step[sx][sy]<<endl;
}
}
}
void vInput()
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin>>mp[i][j];
}
}
}
void vGetBfs(int x,int y)
{
queue<TNode> TQueue;
TNode TTemp;
TTemp.x = x;
TTemp.y = y;
save[ans][1] = x;
save[ans][2] = y;
book[x][y] = 1;
TQueue.push(TTemp);
while(!TQueue.empty())
{
TQueue.pop();
for(int i=0;i<4;i++)
{
int tempx = TTemp.x+dx[i];
int tempy = TTemp.y+dy[i];
if(tempx<1||tempy<1||tempx>n||tempy>n||book[tempx][tempy]!=0||mp[tempx][tempy] == mp[TTemp.x][TTemp.y])
{
continue;
}
ans++;
TTemp.x = tempx;
TTemp.y = tempy;
//cout<<tempx<<" "<<tempy<<endl;
save[ans][1] = tempx;
save[ans][2] = tempy;
book[tempx][tempy] = 1;
TQueue.push(TTemp);
}
TTemp = TQueue.front();
}
for(int i=1;i<=ans;i++)
{
step[save[i][1]][save[i][2]] = ans;
}
}