#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n, m;
  cin >> n >> m;
  vector<vector<long long>> a(n, vector<long long>(m));
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> a[i][j];
    }
  }
  const long long inf = (1LL << 60);
  auto getMinPath = [&](long long start) {
    vector<vector<long long>> d(n, vector<long long>(m));
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        d[i][j] = a[i][j] - (start + i + j);
      }
    }
    vector<vector<long long>> dp(n, vector<long long>(m, inf));
    if (d[0][0] >= 0) dp[0][0] = d[0][0];
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        if (d[i][j] < 0) continue;
        if (i > 0) dp[i][j] = min(dp[i][j], dp[i - 1][j] + d[i][j]);
        if (j > 0) dp[i][j] = min(dp[i][j], dp[i][j - 1] + d[i][j]);
      }
    }
    return dp.back().back();
  };
  long long ans = inf;
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      ans = min(ans, getMinPath(a[i][j] - (i + j)));
    }
  }
  cout << ans << endl;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t--) solve();
  return 0;
}
