#include <bits/stdc++.h>
using namespace std;
template <typename... T>
void err(istream_iterator<string> it) {}
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
  cerr << *it << "=" << a << ", ";
  err(++it, args...);
}
const long long inf = 1LL << 60;
const long long md = 1000000007;
void solve() {
  long long n, m;
  cin >> n >> m;
  long long a[n + 1][m + 1];
  for (long long i = 1; i <= n; i++)
    for (long long j = 1; j <= m; j++) cin >> a[i][j];
  long long ans = inf;
  for (long long i = 1; i <= n; i++) {
    for (long long j = 1; j <= m; j++) {
      long long dp[105][105];
      for (long long x = 0; x <= 101; x++)
        for (long long y = 0; y <= 101; y++) dp[x][y] = inf;
      dp[i][j] = 0;
      for (long long x = i; x > 0; x--) {
        for (long long y = j; y > 0; y--) {
          if (i == x && j == y) continue;
          long long r = a[i][j] - (i - x) - (j - y);
          if (a[x][y] >= r)
            dp[x][y] = min(dp[x + 1][y], dp[x][y + 1]) + a[x][y] - r;
        }
      }
      long long x = dp[1][1];
      for (long long x = 0; x <= 101; x++)
        for (long long y = 0; y <= 101; y++) dp[x][y] = inf;
      dp[i][j] = 0;
      for (long long x = i; x <= n; x++)
        for (long long y = j; y <= m; y++) {
          if (i == x && j == y) continue;
          long long r = a[i][j] - (i - x) - (j - y);
          if (a[x][y] >= r)
            dp[x][y] = min(dp[x - 1][y], dp[x][y - 1]) + a[x][y] - r;
        }
      ans = min(ans, x + dp[n][m]);
    }
  }
  cout << ans;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  cin >> t;
  for (long long i = 1; i <= t; i++) {
    solve();
    cout << '\n';
  }
}
