#include <bits/stdc++.h>
using namespace std;
const long long N = 4e5 + 5, M = 1e5 + 3, OO = 0x3f3f3f3f;
long long t, n, m;
long long a[105][105], ch[105][105];
long long v[4];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (int i = 0; i < n; ++i)
      for (int j = 0; j < m; ++j) cin >> a[i][j];
    long long ans = 0;
    for (int i = 0; i <= n / 2; ++i) {
      for (int j = 0; j <= m / 2; ++j) {
        v[0] = a[i][j];
        v[1] = a[i][m - j - 1];
        v[2] = a[n - i - 1][j];
        v[3] = a[n - i - 1][m - j - 1];
        sort(v, v + 4);
        ch[i][j] = ch[i][m - j - 1] = ch[n - i - 1][j] =
            ch[n - i - 1][m - j - 1] = v[1];
      }
    }
    for (int i = 0; i < n; ++i)
      for (int j = 0; j < m; ++j) ans += abs(ch[i][j] - a[i][j]);
    cout << ans << endl;
  }
  return 0;
}
