#include <bits/stdc++.h>
using namespace std;
struct node{
int x,y,step;
};
queue<node> q;
int dis[4][2]={{1,0},{0,1},{0,-1},{-1,0}},ans;
int n,t;
char a[1005][1005];
int book[1005][1005];
int main()
{
cin>>n>>t;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
cin>>a[i][j];
while(t--)
{
memset(book,0,sizeof(book));
int sx,sy;
cin>>sx>>sy;
q.push(node{sx,sy,0});
ans=0;
while(!q.empty())
{
int nx=q.front().x;
int ny=q.front().y;
int step1=q.front().step;
q.pop();
for(int k=0;k<4;k++)
{
int x1=nx+dis[k][0];
int y1=ny+dis[k][1];
if(x1>=1&&x1<=n&&y1>=1&&y1<=n&&book[x1][y1]==0&&((a[x1][y1]=='1'&&a[nx][ny]=='0')||(a[x1][y1]=='0'&&a[nx][ny]=='1')))
{
book[x1][y1]=1;
q.push(node{x1,y1,step1+1});
ans=max(ans,step1+1);
}
}
}
cout<<ans<<endl;;
}
return 0;
}