#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
long double pi = 3.14159265358979323846;
clock_t time_p = clock();
void rtime() {
  time_p = clock() - time_p;
  cerr << "Time Taken : " << fixed << (float)(time_p) / CLOCKS_PER_SEC << "\n";
}
bool isPrime(long long n) {
  for (long long i = 2; i * i <= n; ++i) {
    if (n % i == 0) {
      return false;
    }
  }
  return true;
}
long long factorial(long long n) {
  return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);
}
long long power(long long x, long long y) {
  long long res = 1;
  x = x;
  while (y > 0) {
    if (y & 1) res = (res * x) % mod;
    y = y >> 1;
    x = (x * x) % mod;
  }
  return res % mod;
}
long long ncr(long long n, long long r) {
  long long res = 1;
  if (r > n) return 0;
  if (r > n - r) r = n - r;
  for (long long i = 0; i < r; i++) {
    res *= (n - i);
    res /= (i + 1);
  }
  return res;
}
long long gcd(long long a, long long b) {
  if (a == 0) return b;
  return gcd(b % a, a);
}
long long lcm(long long a, long long b) { return (a / gcd(a, b) * b); }
long long max(long long a, long long b) {
  long long ans = a > b ? a : b;
  return ans;
}
long long min(long long a, long long b) {
  long long ans = a < b ? a : b;
  return ans;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  long long t, n, m;
  cin >> t;
  while (t--) {
    cin >> n >> m;
    long long a[n][m];
    long long ans = 0;
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        cin >> a[i][j];
      }
    }
    for (long long j = 0; j < n / 2; j++) {
      for (long long i = 0; i < m / 2; i++) {
        vector<long long> v;
        v.push_back(a[j][i]);
        v.push_back(a[n - j - 1][i]);
        v.push_back(a[j][m - i - 1]);
        v.push_back(a[n - j - 1][m - i - 1]);
        sort(v.begin(), v.end());
        long long x = (v[1] + v[2]) / 2;
        ans += abs(x - a[j][i]) + abs(x - a[n - j - 1][i]) +
               abs(x - a[j][m - i - 1]) + abs(x - a[n - j - 1][m - i - 1]);
      }
    }
    if (n % 2 == 1) {
      for (long long i = 0; i < m / 2; i++) {
        ans += abs(a[n / 2][i] - a[n / 2][m - i - 1]);
      }
    }
    if (m % 2 == 1) {
      for (long long i = 0; i < n / 2; i++) {
        ans += abs(a[i][m / 2] - a[n - i - 1][m / 2]);
      }
    }
    cout << ans << "\n";
  }
  rtime();
}
