#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define fo(i,a,b) for(i=a;i<=b;i++)
#define fod(i,a,b) for(i=a;i>=b;i--)
using namespace std;
const int maxn=1007;
int i,j,k,l,t,n,m,cas,r,mid,ans,p,q,yi,er1,lef,rig;
int x,y,xx,yy;
int a[maxn][maxn],f[maxn][maxn];
int g[11][11][maxn][maxn],er[11];
int get(){
char ch=getchar();
int x=0;
while(ch<'0'||ch>'9')ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x;
}
int pan(int xx,int yy,int x,int y){
int i,j,t=0,k=0,ans=0,q;
while (x+(1<<(t+1))-1<=xx)t++;
while (y+(1<<(k+1))-1<=yy)k++;
ans=g[t][k][xx][yy];
if(g[t][k][x+(1<<t)-1][y+(1<<k)-1]>ans)ans=g[t][k][x+(1<<t)-1][y+(1<<k)-1];
if(g[t][k][x+(1<<t)-1][yy]>ans)ans=g[t][k][x+(1<<t)-1][yy];
if(g[t][k][xx][y+(1<<k)-1]>ans)ans=g[t][k][xx][y+(1<<k)-1];
return ans;
}
int main(){
// freopen("fan.in","r",stdin);
// freopen("fan.out","w",stdout);
freopen("square.in","r",stdin);
freopen("square.out","w",stdout);
scanf("%d%d",&n,&m);
er[0]=1;
fo(i,1,10)er[i]=er[i-1]*2;
fo(i,1,n)fo(j,1,m)a[i][j]=get();
for(i=1;i<=n;i++)for(j=1;j<=m;j++){
if(a[i][j]){
g[0][0][i][j]=g[0][0][i-1][j];
if(g[0][0][i][j-1]<g[0][0][i][j])g[0][0][i][j]=g[0][0][i][j-1];
if(g[0][0][i-1][j-1]<g[0][0][i][j])g[0][0][i][j]=g[0][0][i-1][j-1];
g[0][0][i][j]++;
}
}
for(i=0;(1<<i)<=n;i++){
for(j=0;(1<<j)<=m;j++){
if(i==0&&j==0)continue;
for(k=er[i];k<=n;k++)
for(l=er[j];l<=m;l++){
if(j==0){
g[i][j][k][l]=g[i-1][j][k][l];
if(g[i-1][j][k-(1<<(i-1))][l]>g[i][j][k][l])g[i][j][k][l]=g[i-1][j][k-(1<<(i-1))][l];
}
else {
g[i][j][k][l]=g[i][j-1][k][l];
if(g[i][j-1][k][l-(1<<(j-1))]>g[i][j][k][l])g[i][j][k][l]=g[i][j-1][k][l-(1<<(j-1))];
}
}
}
}
for(scanf("%d",&cas);cas;cas--){
x=get(),y=get(),xx=get(),yy=get();
if(pan(xx,yy,x,y)==0){
printf("0\n");
continue;
}
l=0,r=xx-x+1;
if(yy-y+1<r)r=yy-y+1;
while(l<r){
mid=(l+r+1)/2;
if(pan(xx,yy,x+mid-1,y+mid-1)>=mid)l=mid;else r=mid-1;
}
printf("%d\n",l);
}
}