#include<bits/stdc++.h>
struct DSU {
std::vector<int> p;
DSU() = default;
DSU(int n) : p(n) {
std::iota(p.begin(), p.end(), 0);
}
int get(int u) {
while (u != p[u]) u = p[u] = p[p[u]];
return u;
}
bool unite(int u, int v) {
if ((u = get(u)) == (v = get(v))) return false;
p[v] = u;
return true;
}
};
int main() {
std::cin.tie(nullptr)->sync_with_stdio(false);
int n, m;
std::cin >> n >> m;
std::vector<std::vector<int>> r(n, std::vector(m, 1));
auto update = [&](auto update, int x, int y) -> bool {
if (!r[x][y]) return false;
r[x][y] = 0;
if (x > 0 && (y + 1 >= m || !r[x - 1][y + 1])) update(update, x - 1, y);
if (y > 0 && (x + 1 >= n || !r[x + 1][y - 1])) update(update, x, y - 1);
return true;
};
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int x;
std::cin >> x;
if (x) update(update, i, j);
}
}
int q;
std::cin >> q;
while (q--) {
int x, y;
std::cin >> x >> y;
--x, --y;
std::cout << update(update, x, y) << '\n';
}
}