#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1110;
short rmq[10][10][MAXN][MAXN];
long long ps[MAXN][MAXN];
int ps2[MAXN][MAXN], a[MAXN][MAXN], n, m, lg[MAXN];
inline int get(int x1, int y1, int x2, int y2) {
  int i = lg[x2 - x1 + 1], j = lg[y2 - y1 + 1];
  ;
  int ans =
      max(rmq[i][j][x1][y1], rmq[i][j][x2 - (1 << i) + 1][y2 - (1 << j) + 1]);
  int ans2 =
      max(rmq[i][j][x1][y2 - (1 << j) + 1], rmq[i][j][x2 - (1 << i) + 1][y1]);
  return max(ans, ans2);
}
int32_t main() {
  for (int i = 2; i < MAXN; i++) lg[i] = lg[i / 2] + 1;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) scanf("%d", &a[i][j]);
  for (int i = 1; i <= n; i++) {
    ps2[i][0] = a[i][0];
    for (int j = 1; j <= m; j++) ps2[i][j] = ps2[i][j - 1] + a[i][j];
  }
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) ps[i][j] = ps[i - 1][j] + ps2[i][j];
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      int l = 0, r = min(n - i, m - j) + 2;
      while (r - l > 1) {
        long long mid = (l + r) / 2;
        long long k = ps[i + mid - 1][j + mid - 1] + ps[i - 1][j - 1] -
                      ps[i + mid - 1][j - 1] - ps[i - 1][j + mid - 1];
        if (k == mid * mid)
          l = mid;
        else
          r = mid;
      }
      rmq[0][0][i][j] = l;
    }
  }
  for (int k = 1; k < 10; k++)
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++)
        rmq[0][k][i][j] =
            max(rmq[0][k - 1][i][j], rmq[0][k - 1][i][j + (1 << (k - 1))]);
  for (int q = 1; q < 10; q++)
    for (int w = 0; w < 10; w++)
      for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
          rmq[q][w][i][j] =
              max(rmq[q - 1][w][i][j], rmq[q - 1][w][i + (1 << (q - 1))][j]);
  int q;
  scanf("%d", &q);
  int x1, y1, x2, y2;
  while (q--) {
    scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
    int l = 0, r = min(x2 - x1, y2 - y1) + 2;
    while (r - l > 1) {
      int mid = (r + l) / 2;
      int k = get(x1, y1, x2 - mid + 1, y2 - mid + 1);
      if (k >= mid)
        l = mid;
      else
        r = mid;
    }
    printf("%d\n", l);
  }
}
