#include<bits/stdc++.h>
using namespace std ;
char dfs[1005][1005];
int dx[]={0,0,-1,1};
int dy[]={-1,1,0,0};
int n , m , cnt ;
int vis[1005][1005] ;
bool check( int xx ,int yy )
{
if( xx <= n && xx >= 1 && yy <= n && yy >= 1)
{
return 1 ;
}
return 0 ;
}
void chenlaoshi( int x , int y , int ww )
{
for( int i = 0 ; i <= 3 ; i++ )
{
int xx = x + dx[i] ;
int yy = y + dy[i] ;
if( check(xx,yy))
{
if( vis[xx][yy] != ww )
{
if( dfs[xx][yy] == '1' && dfs[x][y] == '0' )
{
vis[xx][yy] = ww ;
cnt++;
chenlaoshi(xx,yy,ww);
}
else if( dfs[xx][yy] == '0' && dfs[x][y] == '1' )
{
vis[xx][yy] = ww ;
cnt++;
chenlaoshi(xx,yy,ww);
}
}
}
}
return ;
}
int main()
{
cin >> n >> m ;
for( int i = 1 ; i <= n ; i ++ )
{
for( int j = 1 ; j <= n ; j++ )
{
cin >> dfs[i][j] ;
}
}
for( int i = 1 ; i <= m ; i++ )
{
cnt = 1 ;
int ex , ey ;
cin >> ex >> ey ;
vis[ex][ey] = i ;
chenlaoshi(ex , ey , i ) ;
cout << cnt << endl ;
}
return 0 ;
}