#include <bits/stdc++.h>
using namespace std;
int main() {
  long long t;
  cin >> t;
  while (t--) {
    long long n, m;
    cin >> n >> m;
    long long arr[n][m];
    for (long long j = 0; j < n; j++) {
      for (long long k = 0; k < m; k++) cin >> arr[j][k];
    }
    long long ct = 0;
    for (long long j = 0; j < n / 2; j++) {
      for (long long k = 0; k < m / 2; k++) {
        long long x, w, z, v;
        x = arr[j][k];
        w = arr[j][m - 1 - k];
        z = arr[n - j - 1][k];
        v = arr[n - j - 1][m - 1 - k];
        long long ans1 = abs(x - v) + abs(x - w) + abs(x - z);
        long long ans2 = abs(v - x) + abs(v - w) + abs(v - z);
        long long ans3 = abs(w - x) + abs(w - v) + abs(w - z);
        long long ans4 = abs(z - x) + abs(z - w) + abs(z - v);
        ct += min(ans1, min(ans2, min(ans3, ans4)));
      }
    }
    if (n % 2 == 1) {
      for (long long k = 0; k < m / 2; k++)
        ct += abs(arr[n / 2][k] - arr[n / 2][m - 1 - k]);
    }
    if (m % 2 == 1) {
      for (long long k = 0; k < n / 2; k++)
        ct += abs(arr[k][m / 2] - arr[n - 1 - k][m / 2]);
    }
    cout << ct << endl;
  }
}
