#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
  while (true) {
    if (a > b) swap(a, b);
    if (a == 0) return b;
    long long p = b % a, q = a;
    a = p;
    b = q;
  }
}
long long powerMod(long long x, long long y) {
  long long res = 1;
  x %= 998244353;
  while (y > 0) {
    if (y & 1) res = (res * x) % 998244353;
    y = y >> 1;
    x = (x * x) % 998244353;
  }
  return res % 998244353;
}
string binary(long long s) {
  string res = "";
  while (s != 0) {
    res += (char)('0' + s % 2);
    s /= 2;
  }
  reverse(res.begin(), res.end());
  return res;
}
vector<vector<long long> > a;
long long solve(long long init_height, int n, int m) {
  long long i, j;
  vector<vector<long long> > dp(n, vector<long long>(m, 1e18));
  if (init_height > a[0][0]) return -1LL;
  dp[0][0] = a[0][0] - init_height;
  for (i = 0LL; i < n; i++) {
    for (j = 0LL; j < m; j++) {
      if (i == 0 && j == 0) continue;
      if (i == 0) {
        if (a[i][j] < init_height + (i + j)) continue;
        dp[i][j] = dp[i][j - 1] + a[i][j] - init_height - i - j;
      } else if (j == 0) {
        if (a[i][j] < init_height + (i + j)) continue;
        dp[i][j] = dp[i - 1][j] + a[i][j] - init_height - i - j;
      } else {
        if (a[i][j] < init_height + (i + j)) continue;
        dp[i][j] =
            min(dp[i - 1][j], dp[i][j - 1]) + a[i][j] - init_height - i - j;
      }
    }
  }
  return dp[n - 1][m - 1];
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  int t, n, m, k, l;
  long long i, j;
  cin >> t;
  while (t--) {
    a.clear();
    cin >> n >> m;
    a.resize(n, vector<long long>(m));
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        cin >> a[i][j];
      }
    }
    long long ans = LLONG_MAX;
    for (i = 0LL; i < n; i++) {
      for (j = 0LL; j < m; j++) {
        long long p = solve(a[i][j] - i - j, n, m);
        if (p >= 0LL) ans = min(ans, p);
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
