#include <bits/stdc++.h>
using namespace std;
long long int function_var = INT_MIN;
void solve(long long int data[], long long int start, long long int end,
           long long int solve_sum, long long int flag) {
  function_var = max(function_var, solve_sum);
  if (end < start) {
    return;
  }
  for (long long int i = start; i <= end; i++) {
    if (flag == 0) {
      solve(data, i + 1, end, solve_sum + data[i], 1);
    } else {
      solve(data, i + 1, end, solve_sum - data[i], 0);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  long long int t;
  t = 1;
  cin >> t;
  while (t--) {
    long long int i, j, k, temp, m, n, count = 0, flag, a, b, val, total = 0,
                                       size, q, c, d;
    cin >> n >> m;
    long long int data[n][m];
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        cin >> data[i][j];
      }
    }
    long long int store[4];
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        store[0] = data[i][j];
        store[1] = data[n - 1 - i][j];
        store[2] = data[i][m - j - 1];
        store[3] = data[n - 1 - i][m - j - 1];
        sort(store, store + 4);
        val = min(1 + store[1], store[2]);
        for (auto x : store) {
          total += abs(val - x);
        }
      }
    }
    cout << total / 4 << endl;
  }
  return 0;
}
