#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
template <typename T>
using lim = numeric_limits<T>;
template <typename T>
istream& operator>>(istream& is, vector<T>& a) {
  for (T& x : a) {
    is >> x;
  }
  return is;
}
template <typename X, typename Y>
istream& operator>>(istream& is, pair<X, Y>& p) {
  return is >> p.first >> p.second;
}
const int N = 100;
ll a[N][N];
unsigned long long INF = lim<unsigned long long>::max();
unsigned long long opt[N][N];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> a[i][j];
      }
    }
    unsigned long long ans = INF;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        for (int ii = 0; ii < n; ii++) {
          for (int jj = 0; jj < m; jj++) {
            if (a[ii][jj] < (a[i][j] + (ii + jj) - (i + j))) {
              opt[ii][jj] = INF;
            } else {
              opt[ii][jj] = a[ii][jj] - (a[i][j] + (ii + jj) - (i + j));
              unsigned long long x = 0;
              if (ii > 0 and jj == 0) {
                x = opt[ii - 1][jj];
              } else if (ii == 0 and jj > 0) {
                x = opt[ii][jj - 1];
              } else if (ii > 0 and jj > 0) {
                x = min(opt[ii - 1][jj], opt[ii][jj - 1]);
              }
              if (x == INF) {
                opt[ii][jj] = INF;
              } else {
                opt[ii][jj] += x;
              }
            }
          }
        }
        ans = min(ans, opt[n - 1][m - 1]);
      }
    }
    cout << ans << endl;
  }
  return 0;
}
