#include <bits/stdc++.h>
using namespace std;
int a[1005][1005];
int bit[1005][1005];
int low(int p) { return p & (-p); }
void merg(int x, int y, int n, int m, int k) {
  while (x <= n) {
    int p = y;
    while (p <= m) {
      bit[x][p] += k;
      p = p + low(p);
    }
    x = x + low(x);
  }
}
int sum(int x, int y) {
  int s = 0;
  while (x) {
    int p = y;
    while (p) {
      s += bit[x][p];
      p = p - low(p);
    }
    x = x - low(x);
  }
  return s;
}
int ans[1000006];
struct pi {
  int x1, y1, x2, y2;
  int id;
};
struct p1 {
  int x, y;
};
vector<p1> gg[1005];
int n, m;
int find(int x1, int y1, int x2, int y2) {
  int w = sum(x2, y2);
  w -= sum(x2, y1 - 1);
  w -= sum(x1 - 1, y2);
  w += sum(x1 - 1, y1 - 1);
  return w;
}
void solve(vector<pi> g, int l, int r) {
  if (l == r) {
    for (pi v : g) {
      ans[v.id] = l;
    }
    for (p1 v : gg[l]) {
      merg(v.x, v.y, n, m, 1);
    }
    return;
  }
  int mid = (l + r) / 2;
  vector<pi> g1, g2;
  g1.clear();
  g2.clear();
  for (int i = mid + 1; i <= r; i++) {
    for (p1 v : gg[i]) {
      merg(v.x, v.y, n, m, 1);
    }
  }
  for (pi v : g) {
    if (v.x2 - v.x1 < mid || v.y2 - v.y1 < mid) {
      g1.push_back(v);
    } else {
      if (find(v.x1 + mid, v.y1 + mid, v.x2, v.y2) > 0) {
        g2.push_back(v);
      } else
        g1.push_back(v);
    }
  }
  for (int i = mid + 1; i <= r; i++) {
    for (p1 v : gg[i]) {
      merg(v.x, v.y, n, m, -1);
    }
  }
  solve(g2, mid + 1, r);
  solve(g1, l, mid);
}
vector<pi> g;
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      scanf("%d", &a[i][j]);
      if (a[i][j]) merg(i, j, n, m, 1);
      int ma = 0;
      if (a[i][j]) {
        int le = 1;
        int ri = min(i, j);
        while (le <= ri) {
          int mid = (le + ri) / 2;
          if (find(i - mid + 1, j - mid + 1, i, j) == mid * mid) {
            le = mid + 1;
          } else
            ri = mid - 1;
        }
        ma = ri;
      }
      p1 pp;
      pp.x = i;
      pp.y = j;
      gg[ma].push_back(pp);
    }
  }
  memset(bit, 0, sizeof(bit));
  int q;
  scanf("%d", &q);
  for (int i = 0; i < q; i++) {
    pi pp;
    scanf("%d%d%d%d", &pp.x1, &pp.y1, &pp.x2, &pp.y2);
    pp.id = i;
    g.push_back(pp);
  }
  solve(g, 0, min(n, m));
  for (int i = 0; i < q; i++) printf("%d\n", ans[i]);
}
