#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long 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 res = 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<long long, long long>> f;
        f.emplace(i, j);
        f.emplace(i, m - 1 - j);
        f.emplace(n - 1 - i, j);
        f.emplace(n - 1 - i, m - 1 - j);
        long long sum = 0;
        vector<long long> F;
        for (auto [i1, j1] : f) sum += a[i1][j1], F.push_back(a[i1][j1]);
        sort(F.begin(), F.end());
        long long mid = F[F.size() / 2];
        long long res1 = 0;
        for (auto [i1, j1] : f) res += abs(mid - a[i1][j1]);
        a[i][j] = a[i][m - 1 - j] = a[n - 1 - i][j] = a[n - 1 - i][m - 1 - j] =
            -1;
        res += res1;
      }
    }
    cout << res << '\n';
  }
}
