#include<bits/stdc++.h>
using namespace std;
int n, m, f[1000005];
bitset<1005> bs[1005];
int id(int i, int j){
return (i - 1) * n + j;
}int find(int x){
return f[x] == x? x: f[x] = find(f[x]);
}void uni(int x, int y){
f[find(x)] = find(y);
}signed main(){
scanf("%d%d", &n, &m);
iota(f, f + n * n + 1, 0);
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
int k;
scanf("%1d", &k);
bool bl = k;
bs[i][j] = bl;
}
}for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
if(i != n and (bs[i][j] xor bs[i + 1][j]))
uni(id(i, j), id(i + 1, j));
if(j != n and (bs[i][j] xor bs[i][j + 1]))
uni(id(i, j), id(i, j + 1));
}
}while(m--){
int x, y, cnt = 0;
scanf("%d%d", &x, &y);
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j)
cnt += find(id(x, y)) == find(id(i, j));
}printf("%d\n", cnt);
}return 0;
}