#include <bits/stdc++.h>
using namespace std;
long long powermod(long long x, long long y) {
  if (y == 0) return 1;
  long long temp = powermod(x, y / 2) % 1000000007;
  if (y % 2) {
    return (((temp * temp) % 1000000007) * x % 1000000007);
  }
  return (temp * temp) % 1000000007;
}
long long power(long long x, long long y) {
  if (y == 0) return 1;
  long long temp = power(x, y / 2);
  if (y % 2) {
    return (((temp * temp)) * x);
  }
  return (temp * temp);
}
void solve() {
  long long n, m, i, j, z;
  cin >> n >> m;
  long long a[n][m];
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) cin >> a[i][j];
  }
  vector<long long> d;
  long long ans2 = 0;
  for (long long k = 0; k <= n / 2; k++) {
    for (long long l = 0; l <= m / 2; l++) {
      for (long long i = 0; i < n; i++) {
        for (long long j = 0; j < m; j++) {
          long long x = min(i, n - i - 1);
          long long y = min(j, m - 1 - j);
          if (x == k && y == l) {
            d.push_back(a[i][j]);
          }
        }
      }
      sort(d.begin(), d.end());
      long long m = d[d.size() / 2];
      for (long long h = 0; h < d.size(); h++) {
        ans2 += abs(m - d[h]);
      }
      d.clear();
    }
  }
  cout << ans2 << "\n";
  return;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
