#include <bits/stdc++.h>
using namespace std;
vector<string> vec_splitter(string s) {
  for (char& c : s) c = c == ',' ? ' ' : c;
  stringstream ss;
  ss << s;
  vector<string> res;
  for (string z; ss >> z; res.push_back(z))
    ;
  return res;
}
void debug_out(vector<string> args, int idx) { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(vector<string> args, int idx, Head H, Tail... T) {
  if (idx > 0) cerr << ", ";
  stringstream ss;
  ss << H;
  cerr << args[idx] << " = " << ss.str();
  debug_out(args, idx + 1, T...);
}
void localTest() {}
const long long N = 1e2 + 5, inf = 1e18;
long long A[N][N], dp[N][N], ans = 2 * inf, n, m;
long long solve(long long st) {
  if (st > A[1][1]) return inf;
  dp[1][1] = A[1][1] - st;
  for (long long k = 1; k <= n; ++k) {
    for (long long l = 1; l <= m; ++l) {
      if (k == 1 && l == 1) continue;
      long long val = st + k + l - 2;
      if (val > A[k][l])
        dp[k][l] = inf;
      else {
        long long moves = A[k][l] - val;
        dp[k][l] = inf;
        if (k > 1 && dp[k - 1][l] != inf)
          dp[k][l] = min(dp[k][l], dp[k - 1][l] + moves);
        if (l > 1 && dp[k][l - 1] != inf)
          dp[k][l] = min(dp[k][l], dp[k][l - 1] + moves);
      }
    }
  }
  if (dp[n][m] != inf) ans = min(ans, dp[n][m]);
  return dp[n][m];
}
int main() {
  localTest();
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    ans = 2e18;
    cin >> n >> m;
    for (long long i = 1; i <= n; ++i)
      for (long long j = 1; j <= m; ++j) cin >> A[i][j];
    for (long long i = 1; i <= n; ++i)
      for (long long j = 1; j <= m; ++j) solve(A[i][j] - i - j + 2);
    cout << ans << "\n";
  }
  return 0;
}
