#include <bits/stdc++.h>
using namespace std;
signed main() {
  std::ios::sync_with_stdio(false);
  cin.tie(NULL);
  ;
  long long t;
  cin >> t;
  while (t--) {
    long long n, m;
    cin >> n >> m;
    vector<vector<long long> > A(n, vector<long long>(m, 0));
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        cin >> A[i][j];
      }
    }
    long long ans = 0;
    for (long long i = 0; i < (n + 1) / 2; i++) {
      for (long long j = 0; j < (m + 1) / 2; j++) {
        long long temp = 0, av = 1e10;
        if (i != n - i - 1) {
          if (j != m - 1 - j) {
            vector<long long> P(4);
            P[0] = A[i][j];
            P[1] = A[i][m - 1 - j];
            P[2] = A[n - 1 - i][j];
            P[3] = A[n - 1 - i][m - 1 - j];
            for (long long p = 0; p < 4; p++) {
              long long inc = 0;
              for (long long q = 0; q < 4; q++) {
                inc += abs(P[p] - P[q]);
              }
              av = min(av, inc);
            }
            ans += av;
          } else {
            temp = abs(A[i][j] - A[n - 1 - i][j]);
            ans += temp;
          }
        } else {
          if (j != m - 1 - j) {
            temp = abs(A[i][j] - A[i][m - 1 - j]);
            ans += temp;
          }
        }
      }
    }
    cout << ans << '\n';
  }
}
