#include <bits/stdc++.h>
using namespace std;
int64_t v[105][105];
int64_t solve(vector<int64_t> t) {
  if (t.size() == 1) return 0;
  if (t.size() == 2) return abs(t[0] - t[1]);
  sort(t.begin(), t.end());
  return min(t[1] - t[0] + t[2] - t[1] + t[3] - t[1],
             t[2] - t[1] + t[2] - t[0] + t[3] - t[2]);
}
int64_t fnc(int64_t m, int64_t n) {
  int64_t ans = 0;
  for (int i = 0; i < (m + 1) / 2; i++) {
    for (int j = 0; j < (n + 1) / 2; j++) {
      vector<int64_t> t;
      t.push_back(v[i][j]);
      if (m - 1 - i != i) t.push_back(v[m - i - 1][j]);
      if (n - 1 - j != j) t.push_back(v[i][n - 1 - j]);
      if (n - 1 - j != j && m - 1 - i != i)
        t.push_back(v[m - 1 - i][n - 1 - j]);
      ans += solve(t);
    }
  }
  return ans;
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    int64_t n, m;
    cin >> m >> n;
    for (int i = 0; i < m; i++) {
      for (int j = 0; j < n; j++) cin >> v[i][j];
    }
    cout << fnc(m, n) << endl;
  }
  return 0;
}
