#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int n;
int t;
char map[1001][1001];
int g[1001][1001];
int vis[1001][1001];
long long ans = 1;
queue<pair<int , int>> q;
int fx[] = {0 , -1 , 1 , 0 , 0};
int fy[] = {0 , 0 , 0 , -1 , 1};
int bfs(int x , int y){
ans = 1;
memset(vis , 0 , sizeof vis);
vis[x][y] = 1;
q.push(make_pair(x , y));
while(!q.empty()){
int vx = q.front().first;
int vy = q.front().second;
q.pop();
for(int i = 1;i <= 4;i++){
int newx = vx + fx[i];
int newy = vy + fy[i];
if(newx >= 1 && newx <= n && newy >= 1 && newy <= n && !vis[newx][newy] && g[newx][newy] != g[vx][vy]){
ans++;
vis[newx][newy] = 1;
q.push(make_pair(newx , newy));
}
}
}
return ans;
}
int main(){
cin >> n >> t;
for(int i = 1;i <= n;i++)
for(int j = 1;j <= n;j++)
cin >> map[i][j] , g[i][j] = map[i][j] - '0';
for(int i = 1;i <= t;i++){
int x , y;
cin >> x >> y;
cout << bfs(x , y) << endl;
}
return 0;
}