#include <bits/stdc++.h>
using namespace std;
long long powm(long long a, long long b, long long mod) {
  if (b == 0) return 1;
  if (b % 2 == 0) {
    long long tmp = powm(a, b / 2, mod);
    return (tmp * tmp) % mod;
  } else
    return (a % mod * powm(a, b - 1, mod)) % mod;
}
long long invm(long long a, long long mod) { return powm(a, mod - 2, mod); }
long long mod = 1000000007;
void solve() {
  long long n, m;
  cin >> n >> m;
  long long a[n][m];
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> a[i][j];
    }
  }
  long long ret = 0;
  for (long long i = 0; i < n / 2; i++) {
    for (long long j = 0; j < m / 2; j++) {
      vector<long long> v;
      v.push_back(a[i][j]);
      v.push_back(a[n - 1 - i][j]);
      v.push_back(a[i][m - 1 - j]);
      v.push_back(a[n - 1 - i][m - 1 - j]);
      sort(v.begin(), v.end());
      long long sum = (v[1] + v[2]) / 2;
      long long mn = abs(a[i][j] - sum);
      mn += abs(a[n - 1 - i][j] - sum);
      mn += abs(a[i][m - 1 - j] - sum);
      mn += abs(a[n - 1 - i][m - 1 - j] - sum);
      sum++;
      long long mn1 = abs(a[i][j] - sum);
      mn1 += abs(a[n - 1 - i][j] - sum);
      mn1 += abs(a[i][m - 1 - j] - sum);
      mn1 += abs(a[n - 1 - i][m - 1 - j] - sum);
      sum -= 2;
      long long mn2 = abs(a[i][j] - sum);
      mn2 += abs(a[n - 1 - i][j] - sum);
      mn2 += abs(a[i][m - 1 - j] - sum);
      mn2 += abs(a[n - 1 - i][m - 1 - j] - sum);
      ret += min(min(mn, mn1), mn2);
    }
  }
  if (n % 2 == 1) {
    long long i = n / 2;
    for (long long j = 0; j < m / 2; j++) {
      long long sum = 0;
      sum += a[i][j];
      sum += a[i][m - 1 - j];
      sum /= 2;
      long long mn = abs(a[i][j] - sum);
      mn += abs(a[i][m - 1 - j] - sum);
      sum++;
      long long mn1 = abs(a[i][j] - sum);
      mn1 += abs(a[i][m - 1 - j] - sum);
      ret += min(mn, mn1);
    }
  }
  if (m % 2 == 1) {
    long long j = m / 2;
    for (long long i = 0; i < n / 2; i++) {
      long long sum = 0;
      sum += a[i][j];
      sum += a[n - 1 - i][j];
      sum /= 2;
      long long mn = abs(a[i][j] - sum);
      mn += abs(a[n - 1 - i][j] - sum);
      sum++;
      long long mn1 = abs(a[i][j] - sum);
      mn1 += abs(a[n - 1 - i][j] - sum);
      ret += min(mn, mn1);
    }
  }
  cout << ret << endl;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cout << fixed << setprecision(12);
  long long t = 1, tc = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
