#include <bits/stdc++.h>
using namespace std;
const long long M = 105;
long long t, dp[M][M], n, m, a[M][M], ans;
bool c[M][M];
bool can(long long l) {
  if (l > a[1][1]) return false;
  memset(c, 0, sizeof c);
  c[1][1] = true;
  for (long long i = 1; i <= n; i++)
    for (long long j = 1; j <= m; j++)
      if (a[i][j] - l - i - j + 2 >= 0)
        if (a[i][j - 1] || a[i - 1][j]) c[i][j] = true;
  return c[n][m];
}
int32_t main() {
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (long long i = 1; i <= n; i++)
      for (long long j = 1; j <= m; j++) cin >> a[i][j];
    long long l = -202, r = 1e16, mid;
    while (r - l > 1) {
      mid = (l + r) / 2;
      if (can(mid))
        l = mid;
      else
        r = mid;
    }
    ans = 2e18;
    for (long long x = 1; x <= n; x++)
      for (long long y = 1; y <= m; y++) {
        l = a[x][y] - x - y + 2;
        if (!can(l)) continue;
        for (long long i = 0; i <= n; i++)
          for (long long j = 0; j <= m; j++) dp[i][j] = 2e18;
        dp[1][1] = a[1][1] - l;
        for (long long i = 1; i <= n; i++)
          for (long long j = 1; j <= m; j++)
            if (a[i][j] - l - i - j + 2 >= 0)
              dp[i][j] = min(dp[i][j], min(dp[i - 1][j], dp[i][j - 1]) +
                                           a[i][j] - l - i - j + 2);
        ans = min(ans, dp[n][m]);
      }
    cout << ans << endl;
  }
  return 0;
}
