#include <bits/stdc++.h>
using namespace std;
const long long N = 105, MAX = 1e18;
int n, m;
long long a[N][N];
void read() {
  cin >> n >> m;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) cin >> a[i][j];
  }
}
long long dp[N][N];
long long calc(long long s) {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (i == 0 && j == 0) {
        dp[0][0] = a[0][0] - s;
        continue;
      }
      dp[i][j] = MAX;
      if ((s + i + j) <= a[i][j]) {
        if (i > 0) dp[i][j] = min(dp[i - 1][j], dp[i][j]);
        if (j > 0) dp[i][j] = min(dp[i][j - 1], dp[i][j]);
        dp[i][j] += a[i][j] - s - i - j;
      }
    }
  }
  return dp[n - 1][m - 1];
}
void solve() {
  long long ans = MAX;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (a[i][j] - i - j <= a[0][0]) ans = min(ans, calc(a[i][j] - i - j));
    }
  }
  cout << ans << '\n';
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    read();
    solve();
  }
  return 0;
}
