RT
#include<bits/stdc++.h>
#define fi first
#define se second
#define ll long long
#define pii pair<ll,ll>
using namespace std;
const int N = 1e6 + 10;
const int M = 1000;
ll n,m,x,y,cnt,mxN,mnN = N,ans1,tmp1;
ll distmmm;
char a[M][M];
double db;
ll sum1;
ll pos1;
ll sum[N],ans;
ll qi[N];
ll jing;
vector<ll> vs;
ll b[N];
ll tong[N];
string s,mxS="",mnS,s1,s2;
int i = 0;
bool vis[M][M];
pair<ll,ll> p[N];
struct node{
ll x,y;
};
queue<node> q;
stack<unsigned ll> st;
inline void read(ll &x){
int f=1;x=0;char s=getchar();
while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
x*=f;
}
bool isin(int x,int y){
return x > 0 && y > 0 && x <= n && y <= n;
}
void bfs(ll sx, ll sy){
memset(vis,0 , sizeof vis);
vis[sx][sy] = 1;
q.push({sx,sy});
int dx[] = {1,-1 , 0 , 0};
int dy[] = {0,0,1 , -1};
while(!q.empty()){
node tmp = q.front();
q.pop();
for(int i = 0 ; i < 4; i++){
int nx = tmp.x + dx[i];
int ny = tmp.y + dy[i];
if(!vis[nx][ny] && isin(nx,ny) && ((a[nx][ny] == '0' && a[tmp.x][tmp.y] == '1' ) || (a[nx][ny] == '1' && a[tmp.x][tmp.y] == '0'))){
// 0 -> 1 1 -> 0,ÔÚµØÍ¼ÉÏ£¬Ã»±»Ëѹý
ans++;
q.push({nx,ny});
vis[nx][ny] = 1;
}
}
// mxN = max(mxN,ans);
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i = 1 ; i <= n;i++){
for(int j = 1 ; j <= n; j++){
cin >> a[i][j];
}
}
// for(int i = 1 ; i <= n;i++){
// for(int j = 1; j <= n;j++){
// cout << a[i][j];
// }
// cout << '\n';
// }
while(m--){
int fx,fy;
scanf("%d%d",&fx,&fy);
bfs(fx,fy);
cout << ans +1<< '\n';
ans = 0;
while(!q.empty()) q.pop();
}
return 0;
}