#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 ;
Arr[i][j] = INT_MIN ;
v.pb(val) ;
}
}
sort_a(v) ;
int cur_st = 0 , cur_en = v.size() - 1 ;
for(int i = 0 ; i < n ; i++){
for(int j = i % 2 ; j < m ; j += 2){
Arr[i][j] = v[cur_st++] ;
if(j + 1 < m && Arr[i][j + 1] == INT_MIN) Arr[i][j + 1] = v[cur_en--] ;
if(i + 1 < n && Arr[i + 1][j] == INT_MIN) Arr[i + 1][j] = v[cur_en--] ;
}
}
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 << i << " " << j << " --> " << heart(i , j) << endl ;
}
}
cout << Ans << "\n" ;
}
int main()
{
__Heart__
int t ; cin >> t ; while(t--) solve() ;
}