#include <bits/stdc++.h>
using namespace std;
const int N = 150;
const int inf = 0x3f3f3f3f;
const long long llinf = 3e18;
const long long mod = 998244353LL;
clock_t TIME_START, TIME_END;
void program_end() {}
int n, m;
long long dp[N][N];
long long ans;
long long a[N][N];
inline long long check(long long h) {
  for (int i = 0; i <= n + 1; ++i)
    for (int j = 0; j <= m + 1; ++j) dp[i][j] = llinf;
  dp[1][1] = a[1][1] - h;
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) {
      if (i == 1 && j == 1) continue;
      if (a[i][j] < i + j - 2 + h) continue;
      dp[i][j] = min(min(llinf, dp[i - 1][j] + a[i][j] - (i + j - 2) - h),
                     min(llinf, dp[i][j - 1] + a[i][j] - (i + j - 2) - h));
    }
  }
  if (dp[n][m] == llinf)
    return -1;
  else
    return dp[n][m];
}
void solve() {
  scanf("%d%d", &n, &m);
  ans = LONG_LONG_MAX;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) scanf("%lld", &a[i][j]);
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) {
      if (a[i][j] - (i + j - 2) > a[1][1]) continue;
      long long tmp = check(a[i][j] - (i + j - 2));
      if (tmp < ans && tmp != -1) ans = tmp;
    }
  }
  printf("%lld\n", ans);
}
int main() {
  TIME_START = clock();
  int Test = 1;
  cin >> Test;
  while (Test--) solve();
  TIME_END = clock();
  program_end();
  return 0;
}
