#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using ld = long double;
pii aa, bb, cc, dd;
ll f(ll avg1, vector<vector<ll>> &a) {
  ll ret2 = 0;
  ret2 += abs(a[aa.first][aa.second] - avg1);
  ret2 += abs(a[bb.first][bb.second] - avg1);
  ret2 += abs(a[cc.first][cc.second] - avg1);
  ret2 += abs(a[dd.first][dd.second] - avg1);
  if (aa == cc) {
    ret2 -= abs(a[aa.first][aa.second] - avg1);
    ret2 -= abs(a[bb.first][bb.second] - avg1);
  }
  if (aa == bb) {
    ret2 -= abs(a[aa.first][aa.second] - avg1);
    ret2 -= abs(a[cc.first][cc.second] - avg1);
  }
  return ret2;
}
void solve() {
  int n, m;
  cin >> n >> m;
  vector<vector<ll>> a(n, vector<ll>(m));
  vector<vector<int>> make(n, vector<int>(m));
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> a[i][j];
    }
  ll ans = 0;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      aa = {i, j};
      bb = {n - i - 1, j};
      cc = {i, m - j - 1};
      dd = {n - i - 1, m - j - 1};
      if (make[aa.first][aa.second]) continue;
      make[aa.first][aa.second] = 1;
      make[bb.first][bb.second] = 1;
      make[cc.first][cc.second] = 1;
      make[dd.first][dd.second] = 1;
      ans += min({f(a[aa.first][aa.second], a), f(a[bb.first][bb.second], a),
                  f(a[cc.first][cc.second], a), f(a[dd.first][dd.second], a)});
    }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
}
