#include<bits/stdc++.h>
using namespace std;
int n,m;
int sum=1;
int dx[6]={0,0,0,-1,1};
int dy[6]={0,-1,1,0,0};
char a[1005][1005];
bool b[1005][1005];
void dfs( int x, int y, int step ){
cout << x << y << step << endl;
for( int i=1; i<=4; i++ ){
int xx=x+dx[i];
int yy=y+dy[i];
if( (a[x][y]=='1' and a[xx][yy]=='0') or (a[x][y]=='0' and a[xx][yy]=='1') and xx>0 and yy>0 and xx<=n and yy<=n and !b[xx][yy] ){
sum++;
//cout<<xx<<" "<<yy<<" ";
b[xx][yy]=1;
dfs( xx,yy,step+1 );
}
}
}
int main(){
//freopen("in.txt","r",stdin);
cin>>n>>m;
for( int i=1; i<=n; i++ ){
for( int j=1; j<=n; j++ ){
cin>>a[i][j];
}
}
int c,d;
for( int i=1; i<=m; i++ ){
memset( b,0,sizeof(b) );
sum=1;
cin>>c>>d;
b[c][d]=1;
dfs( c,d,0 );
cout<<sum/2+1<<"\n";
}
return 0;
}