#include <algorithm>
#include<bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <queue>
#include <string>
using namespace std;
const int N = 1005;
int n , m;
char g[N][N];
int mem[N][N];
typedef pair<int , int >PII;
bool vis[N][N];
queue<PII> que,que1;
int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,-1,1};
int bfs(int x , int y){
int cnt = 1;
vis[x][y] = true;
memset(vis,false, sizeof(vis));
que.push({x,y});
while(!que.empty()){
PII t = que.front();
que1.push(t);
que.pop();
for(int i = 0 ; i < 4 ;i++){
int xx = t.first + dx[i] , yy = t.second + dy[i];
if(((g[t.first][t.second] == '0' && g[xx][yy] == '1') || (g[t.first][t.second] == '1' && g[xx][yy]== '0'))&& (xx >= 1 && xx <= n && yy >=1 && yy <=n) && (!vis[xx][yy]))
{
que.push({xx,yy});
cnt++;
vis[xx][yy] = true;
}
}
}
PII temp ;
while(!que1.empty()){
temp = que1.front();
que1.pop();
mem[temp.first][temp.second] = cnt;
}
return cnt;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin >> n >> m;
for(int i = 1 ; i <= n;i++){
for(int j = 1 ;j<=n;j++){
cin >> g[i][j];
}
}
int x , y;
while(m--){
cin >> x >> y;
if(mem[x][y]!=0) cout << mem[x][y]<<"\n";
else{
int result = bfs(x, y);
cout << result << "\n";
}
}
return 0;
}