#include <bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define fore(i,a,b) for(lli i = (a), abcdxd = (b); i < abcdxd; i++)
#define f first
#define s second
#define pb push_back
#define ENDL '\n'
#define sz(s) lli((s).size())
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
using namespace std;
typedef long long lli;
typedef pair<lli,lli> ii;
typedef vector<lli> vi;
typedef vector<ii> vii;
typedef long double ld;
#define deb(x) cout << #x << ": " << x << endl;
const lli N = 1e3 + 5;
lli n, m;
vii low = {{+1, 0}, {0, +1}};
vii hih = {{-1, 0}, {0, -1}};
lli sum[N+N];
bool nt[N][N];
bool val(lli x, lli y){
return (0 <= x and x < n and 0 <= y and y < m);
}
bool ch(lli x, lli y){
return (0 <= x and x < n and 0 <= y and y < m) and (nt[x][y] == false);
}
void go_dw(lli x, lli y){
if (nt[x][y]) return;
bool fl = false;
for (auto& p : low) fl = (ch(x - p.f, y - p.s) ? true : fl);
if (fl) return;
sum[x+y]--;
nt[x][y] = true;
for (auto& p : low) if (val(x + p.f, y + p.s)) go_dw(x + p.f, y + p.s);
}
void go_up(lli x, lli y){
if (nt[x][y]) return;
bool fl = false;
for (auto& p : hih) fl = (ch(x - p.f, y - p.s) ? true : fl);
if (fl) return;
sum[x+y]--;
nt[x][y] = true;
for (auto& p : hih) if (val(x + p.f, y + p.s)) go_up(x + p.f, y + p.s);
}
lli query(lli x, lli y){
if (nt[x][y]) return 1;
if (sum[x+y] <= 1) return 0;
nt[x][y] = true;
sum[x+y]--;
for (auto& p : low) if (val(x + p.f, y + p.s)) go_dw(x + p.f, y + p.s);
for (auto& p : hih) if (val(x + p.f, y + p.s)) go_up(x + p.f, y + p.s);
return 1;
}
void solve(){
cin >> n >> m;
fore(i,0,n) fore(j,0,m) sum[i+j]++;
fore(i,0,n) fore(j,0,m){
char c; cin >> c; if (c == '1') query(i, j);
}
lli q; cin >> q;
while (q--){
lli x, y; cin >> x >> y; x--, y--;
cout << query(x, y) << endl;
// fore(i,0,n){
// fore(j,0,m) cout << nt[i][j] << ' ';
// cout << endl;
// }
}
}
int main(){ _
// freopen("tracing.in", "r", stdin);
// freopen("tracing.out", "w", stdout);
// lli t; cin >> t;
// while (t--)
solve();
return 0;
}