#include <bits/stdc++.h>
using namespace std;
void d(long long &x) { cout << x << endl; }
long long n, m;
long long a[101][101], dp[101][101];
long long x(long long i, long long j, long long val) {
  if (i == n - 1 && j == m - 1) {
    if (val > a[i][j]) {
      return dp[i][j] = 1e18;
    } else {
      return dp[i][j] = a[i][j] - val;
    }
  }
  if (i == n || j == m) {
    dp[i][j] = 1e18;
  }
  if (val > a[i][j]) {
    return dp[i][j] = 1e18;
  }
  if (dp[i][j] != -1) {
    return dp[i][j];
  }
  long long tmp = a[i][j] - val;
  tmp += min(x(i + 1, j, val + 1), x(i, j + 1, val + 1));
  return dp[i][j] = tmp;
}
int32_t 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 >> a[i][j];
      }
    }
    long long ans = INT64_MAX;
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        long long val = a[i][j] - (i + j);
        memset(dp, -1, sizeof(dp));
        val = x(0, 0, val);
        ans = min(ans, val);
      }
    }
    cout << ans << endl;
  }
  return 0;
}
