#include <bits/stdc++.h>
using namespace std;
#define SC scanf
#define PF printf
#define ull unsigned long long
#define ld long double
#define F first
#define S second
#define pb push_back
#define sort_a(a) sort(a.begin(),a.end());
#define sort_d(a) sort(a.rbegin(),a.rend());
#define READ(f) freopen(f, "r", stdin)
#define WRITE(f) freopen(f, "w", stdout)
#define rev(s) reverse(s.begin(),s.end())
#define P(ok) cout << (ok ? "YES\n": "NO\n")
#define __Heart__ ios_base :: sync_with_stdio(false); cin.tie(NULL);
#define ll long long
typedef pair< ll , ll> PII;
const int sz = 505 ;
int Arr[sz][sz] , n , m , val;
int dx[] = {-1 , 0 , 0 , 1} ;
int dy[] = {0 , 1 , -1 , 0} ;
int heart(int x , int y){
int cur = INT_MAX ;
for(int i = 0 ; i < 4 ; i++){
int cur_i = dx[i] + x ;
int cur_j = dy[i] + y ;
if(cur_i >= 0 && cur_i < n && cur_j >= 0 && cur_j < m){
cur = min(cur , Arr[cur_i][cur_j] + Arr[x][y]) ;
}
}
return cur ;
}
void solve()
{
cin >> n >> m ;
vector < int > v ;
vector < PII > V ;
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < m ; j++){
cin >> val ;
v.pb(val) ;
}
}
sort_a(v) ;
int st = 0 , en = v.size() - 1 , pos_i = 0 , pos_j = 0;
while(st < en){
V.pb({v[st] , v[en]}) ;
st++ ;
en-- ;
}
if(st == en) V.pb({v[st] , v[en]}) ;
// for(auto it : V){
// cout << it.F << " " << it.S << endl ;
// }
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < m ; j++){
int cur = i + j ;
if(cur & 1) Arr[i][j] = V[pos_j++].S ;
else Arr[i][j] = V[pos_i++].F ;
}
}
int Ans = INT_MAX ;
for(int i = 0 ; i < n ; i++){
for(int j = 0 ; j < m ; j++){
Ans = min(Ans , heart(i , j)) ;
}
}
cout << Ans << "\n" ;
}
int main()
{
__Heart__
int t ; cin >> t ; while(t--) solve() ;
}