#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n, m, i, j, a[104][105], m1, m2, a1, a2, ans, t, b[10];
  cin >> t;
  while (t--) {
    ans = 0;
    cin >> n >> m;
    for (i = 1; i <= n; i++) {
      for (j = 1; j <= m; j++) {
        cin >> a[i][j];
      }
    }
    for (i = 1; i <= (n + 1) / 2; i++) {
      for (j = 1; j <= (m + 1) / 2; j++) {
        if (n % 2 && m % 2 && i == (n + 1) / 2 && j == (m + 1) / 2) {
          continue;
        }
        if (n % 2 && i == (n + 1) / 2) {
          ans += abs(a[i][j] - a[i][m - j + 1]);
          continue;
        }
        if (m % 2 && j == (m + 1) / 2) {
          ans += abs(a[i][j] - a[n - i + 1][j]);
          continue;
        }
        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);
        m2 = (b[1] + b[2]) / 2;
        a1 = abs(m2 - a[i][j]) + abs(m2 - a[n - i + 1][j]) +
             abs(m2 - a[n - i + 1][m - j + 1]) + abs(m2 - a[i][m - j + 1]);
        m2 = m2 + 1;
        a2 = abs(m2 - a[i][j]) + abs(m2 - a[n - i + 1][j]) +
             abs(m2 - a[n - i + 1][m - j + 1]) + abs(m2 - a[i][m - j + 1]);
        ans += min(a1, a2);
      }
    }
    cout << ans << endl;
  }
  return 0;
}
