#include <bits/stdc++.h>
using namespace std;
long long int minCost(long long int A[], int n) {
  long long int cost = 0;
  sort(A, A + n);
  long long int K = A[n / 2];
  for (int i = 0; i < n; ++i) cost += abs(A[i] - K);
  if (n % 2 == 0) {
    long long int tempCost = 0;
    K = A[(n / 2) - 1];
    for (int i = 0; i < n; ++i) tempCost += abs(A[i] - K);
    cost = min(cost, tempCost);
  }
  return cost;
}
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int m;
    scanf("%d", &m);
    long long int a[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) cin >> a[i][j];
    }
    long long int half = n / 2;
    long long int ans = 0;
    for (int i = 0; i < half; i++) {
      for (int j = 0; j < m / 2; j++) {
        long long int arr[] = {a[i][j], a[n - i - 1][j], a[i][m - j - 1],
                               a[n - 1 - i][m - j - 1]};
        ans += minCost(arr, 4);
      }
    }
    if (n % 2 != 0) {
      long long int avg = 0;
      for (int i = 0, j = m - 1; i < j; i++, j--) {
        avg = 0;
        if (a[n / 2][i] != a[n / 2][j]) {
          avg = a[n / 2][i] + a[n / 2][j];
          avg = avg / 2;
          ans += abs(a[n / 2][i] - avg) + abs(a[n / 2][j] - avg);
        }
      }
    }
    if (m % 2 != 0) {
      for (int i = 0, j = n - 1; i < j; i++, j--) {
        long long int avg = 0;
        if (a[i][m / 2] != a[j][m / 2]) {
          avg = a[i][m / 2] + a[j][m / 2];
          avg /= 2;
          ans += abs(a[i][m / 2] - avg) + abs(a[j][m / 2] - avg);
        }
      }
    }
    cout << ans << endl;
  }
}
