#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using cd = complex<double>;
using ul = unsigned long;
void pr(ll b, ll i, ll j) {
  cout << b << " " << i + 1 << " " << j + 1 << "\n";
  fflush(stdout);
}
bool ch(ll* ar, ll n) {
  for (ll i = 0; i < n; i++) {
    ll ff = 0;
    for (ll j = i - 1; j >= 0; j--) {
      if (ar[i] + 1 == ar[j]) {
        ff++;
      }
      if (ar[i] - 1 == ar[j]) {
        ff++;
      }
    }
    if (ff == 2) {
      return 0;
    }
  }
  return 1;
}
ll mi(vector<ll> ve) {
  sort(ve.begin(), ve.end());
  ll x = ve[ve.size() / 2];
  ll ss = 0;
  for (ll y : ve) {
    ss += abs(y - x);
  }
  return ss;
}
int main() {
  ll t;
  cin >> t;
  while (t--) {
    ll n, m;
    cin >> n >> m;
    ll ans = 0;
    ll ar[n][m], ch[n][m];
    for (ll i = 0; i < n; i++) {
      for (ll j = 0; j < m; j++) {
        cin >> ar[i][j];
        ch[i][j] = 0;
      }
    }
    for (ll i = 0; i < n; i++) {
      for (ll j = 0; j < m; j++) {
        vector<ll> ve;
        if (ch[i][j]) {
          continue;
        }
        ll xi = n - 1 - i, xj = m - 1 - j;
        set<pair<ll, ll>> sp;
        sp.insert(make_pair(i, j));
        sp.insert(make_pair(xi, j));
        sp.insert(make_pair(xi, xj));
        sp.insert(make_pair(i, xj));
        for (auto p : sp) {
          ve.push_back(ar[p.first][p.second]);
        }
        ans += mi(ve);
        ch[i][j] = ch[xi][j] = ch[i][xj] = ch[xi][xj] = 1;
      }
    }
    cout << ans << "\n";
  }
}
