#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t = 1;
  cin >> t;
  for (int tc = 1; tc <= t; ++tc) {
    long long ans = 0;
    int n, m;
    cin >> n >> m;
    int a[n][m], b[m][n];
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        cin >> a[i][j];
        b[j][i] = a[i][j];
      }
    }
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        vector<int> v;
        v.push_back(a[i][j]);
        v.push_back(a[n - 1 - i][j]);
        v.push_back(a[i][m - 1 - j]);
        v.push_back(a[n - 1 - i][m - j - 1]);
        sort(v.begin(), v.end());
        a[i][j] = a[n - 1 - i][j] = a[i][m - j - 1] = a[n - 1 - i][m - 1 - j] =
            v[v.size() / 2];
      }
    }
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        ans += abs(a[i][j] - b[j][i]);
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
