#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    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; i++) {
      for (int j = 0; j < m; j++) {
        long long arr[4] = {a[i][j], a[i][m - 1 - j], a[n - i - 1][m - j - 1],
                            a[n - i - 1][j]};
        sort(arr, arr + 4);
        long long need = arr[1];
        long long cnt = 0;
        cnt += abs(a[i][j] - need);
        a[i][j] = need;
        cnt += abs(a[i][m - 1 - j] - need);
        a[i][m - 1 - j] = need;
        cnt += abs(a[n - i - 1][m - j - 1] - need);
        a[n - i - 1][m - j - 1] = need;
        cnt += abs(a[n - i - 1][j] - need);
        a[n - i - 1][j] = need;
        ans += cnt;
      }
    }
    cout << ans << "\n";
  }
}
