#include <bits/stdc++.h>
int __nextXZW(int v) {
  int t = v | (v - 1);
  int w = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(v) + 1));
  return w;
}
using namespace std;
const long long MOD = (long long)1e9 + 7;
const long long N = 5e5 + 5, inf = 1e15 + 5000;
long long add(long long x, long long y) {
  x += y;
  if (x >= MOD) return x - MOD;
  return x;
}
long long sub(long long x, long long y) {
  x -= y;
  if (x < 0) return x + MOD;
  return x;
}
long long mult(long long x, long long y) { return (x * y) % MOD; }
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int t;
  cin >> t;
  while (t--) {
    long long n, m;
    cin >> n >> m;
    vector<vector<long long>> a(n, vector<long long>(m));
    for (long long i = 0; i < n; i++)
      for (long long j = 0; j < m; j++) cin >> a[i][j];
    long long ans = 0;
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        if (a[i][j] == -1) continue;
        set<pair<int, int>> seen;
        seen.insert({i, j});
        seen.insert({n - 1 - i, j});
        seen.insert({i, m - 1 - j});
        seen.insert({n - 1 - i, m - 1 - j});
        long long sum = 0;
        for (auto& p : seen) {
          sum += a[p.first][p.second];
        }
        long long x = sum / seen.size();
        long long best = inf;
        for (int y = x - 5; y <= x + 5; y++) {
          long long curr = 0;
          for (auto& p : seen) {
            curr += abs(a[p.first][p.second] - y);
          }
          best = min(best, curr);
        }
        for (auto& p : seen) {
          int y = a[p.first][p.second];
          long long curr = 0;
          for (auto& p : seen) {
            curr += abs(a[p.first][p.second] - y);
          }
          best = min(best, curr);
        }
        for (auto& p : seen) {
          a[p.first][p.second] = -1;
        }
        ans += best;
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
