#include <bits/stdc++.h>
using namespace std;
const int inf = (int)(1e9);
long long n, m, i, ans, j, tc;
int main() {
  cin >> tc;
  while (tc--) {
    cin >> n >> m;
    vector<vector<long long> > a(n, vector<long long>(m, 0));
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) cin >> a[i][j];
    }
    ans = 0;
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        vector<long long> b;
        b.push_back(a[i][j]);
        b.push_back(a[i][m - 1 - j]);
        b.push_back(a[n - 1 - i][j]);
        b.push_back(a[n - 1 - i][m - 1 - j]);
        sort(b.begin(), b.end());
        long long avg = b[1];
        ans += abs(avg - a[i][j]);
        a[i][j] = avg;
        ans += abs(avg - a[n - i - 1][j]);
        a[n - i - 1][j] = avg;
        ans += abs(avg - a[i][m - j - 1]);
        a[i][m - j - 1] = avg;
        ans += abs(avg - a[n - i - 1][m - 1 - j]);
        a[n - i - 1][m - j - 1] = avg;
      }
    }
    cout << ans << endl;
  }
}
