#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 101;
int n, m, q, cum[501][N][N], g[N][N];
int main(int argc, char **argv) {
int T;
scanf("%d", &T);
while (T-- != 0) {
scanf("%d%d%d", &n, &m, &q);
int mx = 0;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j) {
scanf("%d", &g[i][j]);
mx = max(mx, g[i][j]);
for (int k = 1; k <= 500; ++k)
cum[k][i][j] = cum[k][i][j - 1] + cum[k][i - 1][j] - cum[k][i - 1][j - 1] + (g[i][j] == k);
}
for (int i = 2; i <= mx; ++i)
for (int j = 1; j <= n; ++j)
for (int k = 1; k <= m; ++k)
cum[i][j][k] += cum[i - 1][j][k];
int a, b, c, d;
while (q-- != 0) {
scanf("%d%d%d%d", &a, &b, &c, &d);
int L = (c - a + 1) * (d - b + 1);
int medIdx = (L + 1) >> 1;
int l = 1, r = mx, res = 0;
while (l <= r) {
int mid = (l + r) >> 1;
int v = cum[mid][c][d] - cum[mid][a - 1][d] - cum[mid][c][b - 1] + cum[mid][a - 1][b - 1];
if (v < medIdx) {
res = mid;
l = mid + 1;
} else
r = mid - 1;
}
printf("%d\n", res + 1);
}
}
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgp0eXBlZGVmIGxvbmcgbG9uZyBsbDsKCmNvbnN0IGludCBOID0gMTAxOwppbnQgbiwgbSwgcSwgY3VtWzUwMV1bTl1bTl0sIGdbTl1bTl07CgppbnQgbWFpbihpbnQgYXJnYywgY2hhciAqKmFyZ3YpIHsKCWludCBUOwoJc2NhbmYoIiVkIiwgJlQpOwoJd2hpbGUgKFQtLSAhPSAwKSB7CgkJc2NhbmYoIiVkJWQlZCIsICZuLCAmbSwgJnEpOwoJCWludCBteCA9IDA7CgkJZm9yIChpbnQgaSA9IDE7IGkgPD0gbjsgKytpKQoJCQlmb3IgKGludCBqID0gMTsgaiA8PSBtOyArK2opIHsKCQkJCXNj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