#include <bits/stdc++.h>
using namespace std;
long long mod = 1e9 + 7;
void test_case() {
  int n, m;
  cin >> n >> m;
  long long a[n][m];
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) cin >> a[i][j];
  long long ans = 0;
  for (int i = 0; i < n / 2; i++) {
    for (int j = 0; j < m / 2; j++) {
      long long v[4] = {a[i][j], a[i][m - j - 1], a[n - i - 1][j],
                        a[n - i - 1][m - j - 1]};
      sort(v, v + 4);
      long long median = (v[1] + v[2]) / 2;
      for (int k = 0; k < 4; k++) {
        ans += abs(v[k] - median);
      }
    }
  }
  if (n & 1) {
    for (int i = 0; i < m / 2; i++) {
      int median = (a[n / 2][i] + a[n / 2][m - i - 1]) / 2;
      ans += abs(a[n / 2][i] - median) + abs(a[n / 2][m - i - 1] - median);
    }
  }
  if (m & 1) {
    for (int i = 0; i < n / 2; i++) {
      int median = (a[i][m / 2] + a[n - i - 1][m / 2]) / 2;
      ans += abs(a[i][m / 2] - median) + abs(a[n - i - 1][m / 2] - median);
    }
  }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  cin >> t;
  while (t--) test_case();
}
