package main
import (
"io"
"os"
)
var st [10][10][1000][1000]int16
var lg2 [1005]int
func main() {
input, _ := io.ReadAll(os.Stdin)
var pos int
nextInt := func() int {
for pos < len(input) && input[pos] <= ' ' {
pos++
}
if pos >= len(input) {
return 0
}
res := 0
for pos < len(input) && input[pos] > ' ' {
res = res*10 + int(input[pos]-'0')
pos++
}
return res
}
n := nextInt()
m := nextInt()
if n == 0 || m == 0 {
return
}
for i := 2; i <= 1000; i++ {
lg2[i] = lg2[i/2] + 1
}
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
val := nextInt()
if val == 1 {
if i == 0 || j == 0 {
st[0][0][i][j] = 1
} else {
min := st[0][0][i-1][j]
if st[0][0][i][j-1] < min {
min = st[0][0][i][j-1]
}
if st[0][0][i-1][j-1] < min {
min = st[0][0][i-1][j-1]
}
st[0][0][i][j] = min + 1
}
} else {
st[0][0][i][j] = 0
}
}
}
for b := 1; b <= lg2[m]; b++ {
for i := 0; i < n; i++ {
for j := 0; j+(1<<b) <= m; j++ {
maxVal := st[0][b-1][i][j]
if st[0][b-1][i][j+(1<<(b-1))] > maxVal {
maxVal = st[0][b-1][i][j+(1<<(b-1))]
}
st[0][b][i][j] = maxVal
}
}
}
for a := 1; a <= lg2[n]; a++ {
for b := 0; b <= lg2[m]; b++ {
for i := 0; i+(1<<a) <= n; i++ {
for j := 0; j+(1<<b) <= m; j++ {
maxVal := st[a-1][b][i][j]
if st[a-1][b][i+(1<<(a-1))][j] > maxVal {
maxVal = st[a-1][b][i+(1<<(a-1))][j]
}
st[a][b][i][j] = maxVal
}
}
}
}
t := nextInt()
out := make([]byte, 0, t*6)
var printInt func(int)
printInt = func(x int) {
if x == 0 {
out = append(out, '0', '\n')
return
}
var buf [20]byte
p := 20
for x > 0 {
p--
buf[p] = byte((x % 10) + '0')
x /= 10
}
out = append(out, buf[p:]...)
out = append(out, '\n')
}
for q := 0; q < t; q++ {
x1 := nextInt() - 1
y1 := nextInt() - 1
x2 := nextInt() - 1
y2 := nextInt() - 1
left := 1
right := x2 - x1 + 1
if y2-y1+1 < right {
right = y2 - y1 + 1
}
ans := 0
for left <= right {
mid := (left + right) / 2
r1 := x1 + mid - 1
c1 := y1 + mid - 1
r2 := x2
c2 := y2
if r1 > r2 || c1 > c2 {
right = mid - 1
continue
}
lr := lg2[r2-r1+1]
lc := lg2[c2-c1+1]
max1 := st[lr][lc][r1][c1]
max2 := st[lr][lc][r2-(1<<lr)+1][c1]
max3 := st[lr][lc][r1][c2-(1<<lc)+1]
max4 := st[lr][lc][r2-(1<<lr)+1][c2-(1<<lc)+1]
res := max1
if max2 > res {
res = max2
}
if max3 > res {
res = max3
}
if max4 > res {
res = max4
}
if res >= int16(mid) {
ans = mid
left = mid + 1
} else {
right = mid - 1
}
}
printInt(ans)
}
os.Stdout.Write(out)
}