#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;
const vii chd = {{-1, +1}, {+1, -1}};
const vii dir = {{0, +1}, {+1, 0}};
const vii CHD = {{+1, -1}, {-1, +1}};
const vii DIR = {{0, -1}, {-1, 0}};
lli n, m;
bool wl[N][N];
bool nt[N][N];
map<lli, lli> sum;
bool val(lli x, lli y){
return (0 <= x and x < n and 0 <= y and y < m);
}
bool ch(lli x, lli y){
if (0 <= x and x < n and 0 <= y and y < m and nt[x][y] == false) return false;
return true;
}
void lock(lli x, lli y){
if (!nt[x][y]) sum[x+y]--;
nt[x][y] = true;
fore(i,0,2) if (val(x + dir[i].f, y + dir[i].s) and ch(x + chd[i].f, y + chd[i].s) and nt[x + dir[i].f][y + dir[i].s] == false) lock(x + dir[i].f, y + dir[i].s);
}
void LICK(lli x, lli y){
if (!nt[x][y]) sum[x+y]--;
nt[x][y] = true;
fore(i,0,2) if (val(x + DIR[i].f, y + DIR[i].s) and ch(x + CHD[i].f, y + CHD[i].s) and nt[x + DIR[i].f][y + DIR[i].s] == false) LICK(x + DIR[i].f, y + DIR[i].s);
}
lli query(const lli x, const lli y){
if (wl[x][y]) return 0;
if (nt[x][x] == false and sum[x+y] <= 1) return 0;
if (nt[x][y]) { wl[x][y] = true; return 1; }
lock(x, y);
LICK(x, y);
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;
}
}
int main(){ _
// freopen("tracing.in", "r", stdin);
// freopen("tracing.out", "w", stdout);
// lli t; cin >> t;
// while (t--)
solve();
return 0;
}