#include <bits/stdc++.h>
using namespace std;
function<void(void)> ____ = []() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
};
const int MAXN = 111;
int n, m;
long long int A[MAXN][MAXN], f[MAXN][MAXN];
bool ok[MAXN][MAXN];
vector<pair<long long int, pair<int, int>>> node;
long long int DP() {
  f[1][1] = 0;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      if (i == 1 and j == 1) {
        f[i][j] = 0;
        continue;
      }
      f[i][j] = INT_FAST64_MAX;
      if (!ok[i][j]) continue;
      if (i > 1 and f[i - 1][j] != INT_FAST64_MAX)
        f[i][j] = min(f[i][j], f[i - 1][j] + A[i][j]);
      if (j > 1 and f[i][j - 1] != INT_FAST64_MAX)
        f[i][j] = min(f[i][j], f[i][j - 1] + A[i][j]);
    }
  return f[n][m];
}
void solve() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      cin >> A[i][j];
      ok[i][j] = false;
    }
  long long int x = A[1][1];
  node.clear();
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      A[i][j] -= x + i + j - 2;
      if (A[i][j] >= 0)
        ok[i][j] = true;
      else
        node.push_back(make_pair(A[i][j], make_pair(i, j)));
    }
  sort(node.begin(), node.end(),
       greater<pair<long long int, pair<int, int>>>());
  long long int ret = INT_FAST64_MAX;
  ret = min(ret, DP());
  for (int i = 0; i < (int)node.size(); i++) {
    ok[node[i].second.first][node[i].second.second] = true;
    long long int rs = DP();
    if (rs == INT_FAST64_MAX) continue;
    ret = min(ret, rs - node[i].first * (n + m - 1));
  }
  cout << ret << endl;
}
int main() {
  ____();
  int t;
  for (cin >> t; t; t--) solve();
  return 0;
}
