#include <bits/stdc++.h>
using namespace std;
void one_case() {
  int n, m;
  cin >> n >> m;
  vector<vector<int>> a(n, vector<int>(m));
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cin >> a[i][j];
    }
  }
  long long total = 0;
  for (int i = 0; 2 * i < n; ++i) {
    for (int j = 0; 2 * j < m; ++j) {
      vector<int> vals = {a[i][j], a[n - 1 - i][j], a[i][m - 1 - j],
                          a[n - 1 - i][m - 1 - j]};
      sort(vals.begin(), vals.end());
      long long best = vals[1];
      total += abs(best - a[i][j]);
      a[i][j] = best;
      total += abs(best - a[n - 1 - i][j]);
      a[n - 1 - i][j] = best;
      total += abs(best - a[i][m - 1 - j]);
      a[i][m - 1 - j] = best;
      total += abs(best - a[n - 1 - i][m - 1 - j]);
      a[n - 1 - i][m - 1 - j] = best;
    }
  }
  cout << total << "\n";
}
int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(nullptr);
  int t = 1;
  cin >> t;
  while (t--) one_case();
  return 0;
}
