mdzz
#include <cstdio>
#include <cstring>
#include <iostream>
#define LL long long
using namespace std;
const LL inf = (LL)1e15;
LL n,m,T,mx;
LL x;
LL a[2];
LL c[2];
LL ar[45][45];
LL gap[1610],h[1610];
struct edge {
LL v,next;
LL f;
}e[16010];
LL cnt,head[1610];
LL read_int () {
char c = getchar();
LL re = 0;
for(;c < '0' || c > '9';c = getchar());
for(;c >= '0' && c <= '9';c = getchar())
re = re * 10 + c - '0';
return re;
}
void adde (LL u,LL v,LL f) {
e[cnt].v = v;
e[cnt].f = f;
e[cnt].next = head[u];
head[u] = cnt++;
e[cnt].v = u;
e[cnt].f = 0;
e[cnt].next = head[v];
head[v] = cnt++;
}
LL cal (LL i,LL j) {
return (i - 1) * m + j;
}
LL dfs (LL u,LL minf) {
if(u == n * m + 1)
return minf;
LL chan = n * m + 1;
LL leftf = minf;
for(LL i = head[u];i != -1;i = e[i].next) {
LL v = e[i].v;
if(e[i].f) {
if(h[v] == h[u] - 1) {
LL t = dfs(v,min(e[i].f,leftf));
e[i].f -= t;
e[i ^ 1].f += t;
leftf -= t;
if(h[0] >= n * m + 2)
return minf - leftf;
if(!leftf)
break;
}
chan = min(chan,h[v]);
}
}
if(minf == leftf) {
if(--gap[h[u]] == 0)
h[0] = n * m + 2;
++gap[h[u] = chan + 1];
}
return minf - leftf;
}
LL sap () {
memset(head,-1,sizeof head);
cnt = 0;
bool f = 0;
for(LL i = 1;i <= n;++i) {
for(LL j = 1;j <= m;++j) {
if(!f)
adde(0,cal(i,j),x - ar[i][j]);
else adde(cal(i,j),n * m + 1,x - ar[i][j]);
if(!f) {
LL uu = i + 1;
LL vv = j;
if(uu >= 1 && uu <= n && vv <= m && vv >= 1)
adde(cal(i,j),cal(uu,vv),inf);
uu = i - 1;
vv = j;
if(uu >= 1 && uu <= n && vv <= m && vv >= 1)
adde(cal(i,j),cal(uu,vv),inf);
uu = i;
vv = j + 1;
if(uu >= 1 && uu <= n && vv <= m && vv >= 1)
adde(cal(i,j),cal(uu,vv),inf);
uu = i;
vv = j - 1;
if(uu >= 1 && uu <= n && vv <= m && vv >= 1)
adde(cal(i,j),cal(uu,vv),inf);
}
f ^= 1;
}
if(!(m & 1))
f ^= 1;
}
memset(gap,0,sizeof gap);
memset(h,0,sizeof h);
gap[0] = n * m + 2;
LL re = 0;
while(h[0] < n * m + 2)
re += dfs(0,inf);
if((LL)c[0] * x - a[0] == re)
return re;
return -1;
}
int main () {
T = read_int();
while(T--) {
n = read_int();
m = read_int();
a[1] = a[0] = c[0] = c[1] = mx = 0;
bool f = 0;
for(LL i = 1;i <= n;++i) {
for(LL j = 1;j <= m;++j) {
c[f]++;
ar[i][j] = read_int();
mx = max(ar[i][j],mx);
a[f] += ar[i][j];
f ^= 1;
}
if(!(m & 1))
f ^= 1;
}
if(c[1] - c[0] == 0) {
if(a[1] != a[0])
printf("-1\n");
else {
LL ans = -1;
LL l = mx,r = inf;
while(l <= r) {
x = (l + r) >> 1;
LL tt = sap();
if(tt != -1) {
ans = tt;
r = x - 1;
}
else l = x + 1;
}
printf("%lld\n",ans);
}
}
else {
if((a[1] - a[0]) / (c[1] - c[0]) * (c[1] - c[0]) != (a[1] - a[0]))
printf("-1\n");
else {
x = (a[1] - a[0]) / (c[1] - c[0]);
if(x < mx)
printf("-1\n");
else printf("%lld\n",sap());
}
}
}
}