#include <bits/stdc++.h>
using namespace std;
int mat[1005][1005];
int sm[1005][1005];
int sq[1005][1005];
short sparse[10][10][1005][1005];
int lg[1005];
void pre(int n, int m) {
  for (int g = 0; g < 10; g++) {
    int lim = min((1 << (g + 1)), 1005);
    for (int i = 1 << g; i < lim; i++) lg[i] = g;
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) sparse[0][0][i][j] = sq[i][j];
    for (int g = 1; (1 << g) <= m; g++) {
      int p2 = 1 << g;
      for (int j = 1; j + p2 - 1 <= m; j++) {
        sparse[g][0][i][j] =
            max(sparse[g - 1][0][i][j], sparse[g - 1][0][i][j + (p2 >> 1)]);
      }
    }
  }
  for (int j = 1; j <= m; j++) {
    for (int g = 0; g <= lg[m - j + 1]; g++) {
      for (int g2 = 1; g2 <= lg[n]; g2++) {
        int p2 = (1 << g2);
        for (int i = 1; i + p2 - 1 <= n; i++) {
          sparse[g][g2][i][j] =
              max(sparse[g][g2 - 1][i][j], sparse[g][g2 - 1][i + (p2 >> 1)][j]);
        }
      }
    }
  }
}
int max2D(int x1, int y1, int x2, int y2) {
  int g2 = lg[x2 - x1 + 1], g = lg[y2 - y1 + 1];
  int f1 = max(sparse[g][g2][x1][y1], sparse[g][g2][x2 - (1 << g2) + 1][y1]);
  int f2 = max(sparse[g][g2][x1][y2 - (1 << g) + 1],
               sparse[g][g2][x2 - (1 << g2) + 1][y2 - (1 << g) + 1]);
  return max(f1, f2);
}
int main() {
  int n, m;
  scanf("%d", &n);
  scanf("%d", &m);
  memset(sm, 0, sizeof(sm));
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      scanf("%d", &mat[i][j]);
      sm[i][j] = mat[i][j] + sm[i][j - 1] + sm[i - 1][j] - sm[i - 1][j - 1];
    }
  }
  memset(sq, 0, sizeof(sq));
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (!mat[i][j]) continue;
      int l = 1, r = min(i, j);
      while (l < r) {
        int mid = (l + r + 1) >> 1;
        int s =
            sm[i][j] - sm[i - mid][j] - sm[i][j - mid] + sm[i - mid][j - mid];
        if (s == mid * mid)
          l = mid;
        else
          r = mid - 1;
      }
      sq[i][j] = l;
    }
  }
  pre(n, m);
  int t;
  scanf("%d", &t);
  while (t--) {
    int x1, y1, x2, y2;
    scanf("%d", &x1);
    scanf("%d", &y1);
    scanf("%d", &x2);
    scanf("%d", &y2);
    int l = 0, r = min(x2 - x1 + 1, y2 - y1 + 1);
    while (l < r) {
      int mid = (l + r + 1) >> 1;
      int q = max2D(x1 + mid - 1, y1 + mid - 1, x2, y2);
      if (q >= mid)
        l = mid;
      else
        r = mid - 1;
    }
    printf("%d\n", l);
  }
}
