#3 TLE
#include<bits/stdc++.h>
#define fi first
#define se second
using namespace std;
int n, m;
int ma[1005][1005], vis[1005][1005], bm[1005][1005];
int xx[4]={1, -1, 0, 0};
int yy[4]={0, 0, 1, -1};
int ans=0;
bool check(int x, int y){
return x >= 1 && x <= n && y >= 1 && y <= n && !vis[x][y];
}
typedef pair <int, int> p;
queue <p> xy;
queue <p> biao;
void bfs(int x, int y){
vis[x][y] = 1;
xy.push({x, y});
while(!xy.empty()){
ans += 1;
int ux = xy.front().fi;
int uy = xy.front().se;
xy.pop();
for(int i=0; i<4; i++){
int tx = ux+xx[i];
int ty = uy+yy[i];
if(check(tx, ty) && (ma[tx][ty] != ma[ux][uy])){
vis[tx][ty] = 1;
xy.push({tx, ty});
biao.push({tx, ty});
}
}
}
}
int main(){
cin >> n >> m;
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
char c;
cin >> c;
ma[i][j] = c-'0';
}
}
for(int i=1; i<=m; i++){
int a, b;
cin >> a >> b;
if(!bm[a][b]){
bfs(a, b);
cout << ans << endl;
while(!biao.empty()){
int x = biao.front().fi;
int y = biao.front().se;
bm[x][y] = ans;
biao.pop();
}
ans = 0;
memset(vis, 0, sizeof vis);
} else{
cout << bm[a][b] << endl;
}
}
return 0;
}