#include <bits/stdc++.h>
using namespace std;
const int N = 1e3 + 86;
typedef pair<int, int> PII;
int n, m, g[N][N],a[N*N], u, v, dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
char t;
bool f[N][N],st[N][N];
int find(int x)
{
if(a[x]!=x)a[x]=find(a[x]);
return a[x];
}
void bfs(int u,int v)
{
queue<PII> q;
q.push({u,v});
st[u][v]=true;
int res=0;
while(q.size())
{
auto t=q.front();
q.pop();
for(int i=0;i<4;i++)
{
int x=t.first+dx[i],y=t.second+dy[i];
if(x>=1&&y>=1&&x<=n&&y<=n&&(!st[x][y])&&f[x][y]^f[t.first][t.second])
{
q.push({x,y});
st[x][y]=true;
a[find(x*1000+y)]=find(t.first*1000+t.second);
res++;
}
}
}
g[u][v]=res+1;
return;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
cin>>t;
if(t=='1')f[i][j]=1;
a[i*1000+j]=i*1000+j;
}
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
if (!st[i][j])
bfs(i, j);
while (m--)
{
scanf("%d%d", &u, &v);
int t=find(u*1000+v);
printf("%d\n", g[t/1000][t%1000]);
}
return 0;
}