#include <bits/stdc++.h>
using namespace std;
int n, m, a[1004][1004], d[1004][1004];
short st[1005][1005][11][11];
int pw[20], lg[1005];
int x, y, xx, yy;
inline bool ck(int len) {
  int sx = x + len - 1, sy = y + len - 1;
  return max(max(st[sx][sy][lg[xx - sx + 1]][lg[yy - sy + 1]],
                 st[xx - pw[lg[xx - sx + 1]] + 1][yy - pw[lg[yy - sy + 1]] + 1]
                   [lg[xx - sx + 1]][lg[yy - sy + 1]]),
             max(st[xx - pw[lg[xx - sx + 1]] + 1][sy][lg[xx - sx + 1]]
                   [lg[yy - sy + 1]],
                 st[sx][yy - pw[lg[yy - sy + 1]] + 1][lg[xx - sx + 1]]
                   [lg[yy - sy + 1]])) >= len;
}
int main() {
  pw[0] = 1, lg[1] = 0;
  for (int i = 1; i <= 20; i++) pw[i] = (pw[i - 1] << 1);
  for (int i = 2; i <= 1001; i++) lg[i] = lg[i >> 1] + 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]);
      st[i][j][0][0] = d[i][j] =
          a[i][j] * (min(min(d[i][j - 1], d[i - 1][j]), d[i - 1][j - 1]) + 1);
    }
  for (int k1 = 0; k1 <= 9; k1++)
    for (int k2 = 0; k2 <= 9; k2++)
      if (k1 | k2)
        for (int i = 1; i <= n; i++)
          for (int j = 1; j <= m; j++)
            if (i + pw[k1] - 1 <= n && j + pw[k2] - 1 <= m) {
              if (k2 != 0)
                st[i][j][k1][k2] = max(st[i][j][k1][k2 - 1],
                                       st[i][j + pw[k2 - 1]][k1][k2 - 1]);
              else
                st[i][j][k1][k2] = max(st[i][j][k1 - 1][k2],
                                       st[i + pw[k1 - 1]][j][k1 - 1][k2]);
            } else
              break;
  int Q;
  scanf("%d", &Q);
  for (int i = 1; i <= Q; i++) {
    scanf("%d%d%d%d", &x, &y, &xx, &yy);
    int lef = 0, rig = min(xx - x + 1, yy - y + 1), mid, ans = 0;
    while (lef <= rig) {
      mid = ((lef + rig) >> 1);
      if (ck(mid))
        ans = mid, lef = mid + 1;
      else
        rig = mid - 1;
    }
    printf("%d\n", ans);
  }
  return 0;
}
