#include <bits/stdc++.h>
using namespace std;
const long long N = 111;
const long long INF = 1e18;
long long a[N][N];
long long f[N][N];
long long n, m;
void run() {
  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 ans = INF;
  for (long long x = 1; x <= n; x++) {
    for (long long y = 1; y <= m; y++) {
      long long now = a[x][y] - x - y + 2;
      for (long long i = 1; i <= n; i++) {
        for (long long j = 1; j <= m; j++) {
          f[i][j] = INF;
        }
      }
      if (a[1][1] >= now) f[1][1] = a[1][1] - now;
      for (long long i = 1; i <= n; i++) {
        for (long long j = 1; j <= m; j++) {
          if (i > 1 && a[i][j] >= now + i + j - 2)
            f[i][j] = min(f[i][j], f[i - 1][j] + a[i][j] - (now + i + j - 2));
          if (j > 1 && a[i][j] >= now + i + j - 2)
            f[i][j] = min(f[i][j], f[i][j - 1] + a[i][j] - (now + i + j - 2));
        }
      }
      ans = min(ans, f[n][m]);
    }
  }
  cout << ans << '\n';
}
signed main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  long long tt;
  cin >> tt;
  while (tt--) run();
  return 0;
}
