#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n, m;
  cin >> n >> m;
  vector<vector<long long> > a(n, vector<long long>(m));
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cin >> a[i][j];
    }
  }
  long long res = 0;
  for (int i = 0; i < n / 2; ++i) {
    for (int j = 0; j < m / 2; ++j) {
      long long res1 = LLONG_MAX;
      vector<long long> vars{a[i][j], a[i][m - 1 - j], a[n - 1 - i][j],
                             a[n - 1 - i][m - 1 - j]};
      for (auto var : vars) {
        long long res2 = 0;
        res2 += abs(var - a[i][j]);
        res2 += abs(var - a[i][m - 1 - j]);
        res2 += abs(var - a[n - 1 - i][j]);
        res2 += abs(var - a[n - 1 - i][m - 1 - j]);
        res1 = min(res1, res2);
      }
      res += res1;
    }
  }
  if (n % 2) {
    int i = n / 2;
    for (int j = 0; j < m / 2; ++j) {
      long long best = (a[i][j] + a[i][m - 1 - j]) / 2;
      res += abs(best - a[i][j]);
      res += abs(best - a[i][m - 1 - j]);
    }
  }
  if (m % 2) {
    int j = m / 2;
    for (int i = 0; i < n / 2; ++i) {
      long long best = (a[i][j] + a[n - 1 - i][j]) / 2;
      res += abs(best - a[i][j]);
      res += abs(best - a[n - 1 - i][j]);
    }
  }
  cout << res << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr), cout.tie(nullptr);
  cout << fixed << setprecision(15);
  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
}
