#include <bits/stdc++.h>
using namespace std;
const long long INF = 2e18;
const long long MB = 31;
const long long MOD = 1e9 + 7;
const long long N = 100;
long long a[N][N], dp[N][N];
long long get(long long n, long long m, long long val) {
  dp[0][0] = a[0][0] < val ? INF : a[0][0] - val;
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      if (!i && !j) continue;
      if (a[i][j] < val + i + j) {
        dp[i][j] = INF;
        continue;
      }
      dp[i][j] = a[i][j] - val - i - j;
      if (min(i ? dp[i - 1][j] : INF, j ? dp[i][j - 1] : INF) == INF)
        dp[i][j] = INF;
      else
        dp[i][j] += min(i ? dp[i - 1][j] : INF, j ? dp[i][j - 1] : INF);
    }
  }
  return dp[n - 1][m - 1];
}
void solve() {
  long long n, m;
  cin >> n >> m;
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> a[i][j];
    }
  }
  long long ans = INF;
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      ans = min(ans, get(n, m, a[i][j] - i - j));
    }
  }
  cout << ans << '\n';
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  cout.precision(12);
  cout << fixed;
  long long t;
  cin >> t;
  while (t--) solve();
}
