#include <bits/stdc++.h>
using namespace std;
long long ar[110][110];
long long dp[110][110];
long long n, m;
long long mn(long long i, long long j, long long num) {
  if (i == (n - 1) && j == (m - 1)) {
    if (ar[i][j] < num)
      return 1e18;
    else {
      return dp[i][j] = ar[i][j] - num;
    }
  }
  if (dp[i][j] != -1) return dp[i][j];
  if (i >= n || j >= m) return 1e18;
  if (num > ar[i][j]) return 1e18;
  long long ch = ar[i][j] - num;
  return dp[i][j] = ch + min(mn(i + 1, j, num + 1), mn(i, j + 1, num + 1));
}
int main() {
  long long t;
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        cin >> ar[i][j];
      }
    }
    long long ans = 1e18;
    long long mx = ar[0][0];
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        memset(dp, -1, sizeof(dp));
        long long num = ar[i][j] - (i + j);
        if (num <= mx) {
          ans = min(mn(0, 0, num), ans);
        }
      }
    }
    cout << ans << "\n";
  }
}
