#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
long long t, n, m, i, k;
long long a[1005][1005];
vector<long long> v;
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> t;
  while (t--) {
    long long j;
    cin >> n >> m;
    for (i = 1; i <= n; i++) {
      for (j = 1; j <= m; j++) cin >> a[i][j];
    }
    long long ans = 0;
    for (i = 1; i <= n / 2 + n % 2; i++) {
      for (j = 1; j <= m / 2 + m % 2; j++) {
        long long mx1 = 0, mx2 = 0, mx3 = 0, mx4 = 0;
        long long x1 = a[i][j], x2 = a[n - i + 1][j],
                  x3 = a[n - i + 1][m - j + 1], x4 = a[i][m - j + 1];
        if (2 * i - 1 != n) {
          mx1 += abs(x2 - x1);
        }
        if (2 * j - 1 != m) {
          mx1 += abs(x4 - x1);
        }
        if (2 * j - 1 != m && 2 * i - 1 != n) mx1 += abs(x3 - x1);
        if (2 * i - 1 != n) {
          mx2 += abs(x2 - x1);
        }
        if (2 * j - 1 != m) {
          mx2 += abs(x4 - x2);
        }
        if (2 * j - 1 != m && 2 * i - 1 != n) mx2 += abs(x3 - x2);
        if (2 * i - 1 != n) {
          mx3 += abs(x4 - x3);
        }
        if (2 * j - 1 != m) {
          mx3 += abs(x2 - x3);
        }
        if (2 * j - 1 != m && 2 * i - 1 != n) mx3 += abs(x3 - x1);
        if (2 * i - 1 != n) {
          mx4 += abs(x3 - x4);
        }
        if (2 * j - 1 != m) {
          mx4 += abs(x4 - x1);
        }
        if (2 * j - 1 != m && 2 * i - 1 != n) mx4 += abs(x2 - x4);
        ans += min(min(mx1, mx2), min(mx3, mx4));
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
