#include<bits/stdc++.h>
using namespace std;
const int N=1e3+3;
const int VL = 3e3+3;
const long long inf=1e18+3;
#define ll long long
#define fi first
#define se second
#define VOI void
int n,m;
int a[N][N];
int tmp[N][N],R[N][N];
int cnt[VL];
int mvx[5] = {1,-1,0,0};
int mvy[5] = {0,0,1,-1};
int othx[5] = {1,-1,-1,1};
int othy[5] = {-1,1,1,-1};
bool chk(int x,int y){
return (x >= 1 && x <= n && y >= 1 && y <= m);
}
VOI jiangly(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>a[i][j];
}
}
memset(tmp,0,sizeof(tmp));
tmp[1][1] = 1;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
int up = tmp[i-1][j] | tmp[i][j-1];
if(!a[i][j])tmp[i][j] += up;
R[i][j] += tmp[i][j];
}
}
memset(tmp,0,sizeof tmp);
tmp[n][m] = 1;
for(int i=n;i>=1;i--){
for(int j=m;j>=1;j--){
int up = tmp[i+1][j] | tmp[i][j+1];
if(!a[i][j])tmp[i][j] += up;
R[i][j] += tmp[i][j];
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(R[i][j] >= 2){
R[i][j] = 0;
}
else R[i][j] = 1;
if(!R[i][j]){
cnt[i+j]++;
}
}
}
int q;
cin>>q;
for(int i=1;i<=q;i++){
int u,v;
cin>>u>>v;
if(R[u][v] == 0 && cnt[u+v] == 1){
cout<<0<<"\n";
}
else{
cout<<1<<"\n";
queue<pair<int,int>>q;
q.push({u,v});
while(!q.empty()){
auto [u,v] = q.front();
q.pop();
if(R[u][v])continue;
R[u][v] = 1;
cnt[u+v]--;
for(int mv=0;mv<4;mv++){
int nx = u + mvx[mv];
int ny = v + mvy[mv];
int ox = u + othx[mv];
int oy = v + othy[mv];
if(chk(nx,ny)){
if(R[nx][ny])continue;
else{
if(chk(ox,oy) && R[ox][oy])q.push({nx,ny});
}
}
}
}
}
}
}
int main(){
cin.tie(0)->sync_with_stdio(0);
if(fopen("QUANSENSEI.inp","r")){
freopen("O(0).inp","r",stdin);
}
// if(fopen("input.txt","r")){
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
// }
jiangly();
// cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
}