#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  while (t--) {
    long long n, i, j = 0, k, l, m, x, y, bugi = 0, chigi = 0, ela = 0,
                    bela = 0;
    cin >> n >> m;
    long long a[n][m], b[4];
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) cin >> a[i][j];
    }
    for (i = 0; i < n / 2; i++) {
      for (j = 0; j < m / 2; j++) {
        b[0] = a[i][j];
        b[1] = a[i][m - j - 1];
        b[2] = a[n - i - 1][j];
        b[3] = a[n - i - 1][m - j - 1];
        sort(b, b + 4);
        bugi += (abs(b[0] - b[1]) + abs(b[1] - b[2]) + abs(b[1] - b[3]));
      }
    }
    if (n % 2) {
      for (i = 0; i < m / 2; i++)
        bugi += abs(a[n / 2][i] - a[n / 2][m - i - 1]);
    }
    if (m % 2) {
      for (i = 0; i < n / 2; i++)
        bugi += abs(a[i][m / 2] - a[n - i - 1][m / 2]);
    }
    cout << bugi << "\n";
  }
  return 0;
}
