#include <bits/stdc++.h>
using namespace std;
void shikhar7s(long long int cas) {
  long long int n, m, i, j, l;
  cin >> n >> m;
  long long int a[n][m];
  vector<long long int> v;
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      cin >> a[i][j];
      a[i][j] -= (i + j);
      v.push_back(a[i][j]);
    }
  }
  long long int ans = 2000000000000000000;
  for (l = 0; l < (long long int)v.size(); l++) {
    long long int dp[n][m];
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        if (!i && !j) {
          if (a[i][j] >= v[l])
            dp[i][j] = a[i][j] - v[l];
          else
            dp[i][j] = 2000000000000000000;
        } else if (!i) {
          if (a[i][j] >= v[l])
            dp[i][j] = a[i][j] - v[l];
          else
            dp[i][j] = 2000000000000000000;
          if (dp[i][j] != 2000000000000000000 &&
              dp[i][j - 1] != 2000000000000000000)
            dp[i][j] += dp[i][j - 1];
          else
            dp[i][j] = 2000000000000000000;
        } else if (!j) {
          if (a[i][j] >= v[l])
            dp[i][j] = a[i][j] - v[l];
          else
            dp[i][j] = 2000000000000000000;
          if (dp[i][j] != 2000000000000000000 &&
              dp[i - 1][j] != 2000000000000000000)
            dp[i][j] += dp[i - 1][j];
          else
            dp[i][j] = 2000000000000000000;
        } else {
          if (a[i][j] >= v[l])
            dp[i][j] = a[i][j] - v[l];
          else
            dp[i][j] = 2000000000000000000;
          if (dp[i][j] != 2000000000000000000 &&
              min(dp[i][j - 1], dp[i - 1][j]) != 2000000000000000000)
            dp[i][j] += min(dp[i][j - 1], dp[i - 1][j]);
          else
            dp[i][j] = 2000000000000000000;
        }
      }
    }
    ans = min(ans, dp[n - 1][m - 1]);
  }
  cout << ans << "\n";
}
signed main() {
  std::ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  long long int t = 1;
  cin >> t;
  long long int cas = 1;
  while (cas <= t) {
    shikhar7s(cas);
    cas++;
  }
  return 0;
}
