#include <bits/stdc++.h>
using namespace std;
const int inf = 2e9;
const long long INF = 8e18;
const int maxn = 1e2 + 5;
const int maxm = 1e4 + 5;
int n, m;
long long a[maxn][maxn], dp[maxn][maxn];
inline long long DP(long long val) {
  for (int i = 0; i < maxn; ++i)
    for (int j = 0; j < maxn; ++j) dp[i][j] = INF;
  if (a[1][1] < val) return INF;
  dp[1][1] = a[1][1] - val;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) {
      if (i == 1 && j == 1) continue;
      if (a[i][j] >= val)
        dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + a[i][j] - val;
    }
  return dp[n][m];
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int T;
  cin >> T;
  while (T--) {
    for (int i = 0; i < maxn; ++i)
      for (int j = 0; j < maxn; ++j)
        for (int k = 0; k < maxm; ++k) dp[i][j] = INF;
    cin >> n >> m;
    for (int i = 1; i <= n; ++i)
      for (int j = 1; j <= m; ++j) {
        cin >> a[i][j];
        a[i][j] -= i + j;
      }
    long long ans = INF;
    for (int i = 1; i <= n; ++i) {
      for (int j = 1; j <= m; ++j) {
        ans = min(DP(a[i][j]), ans);
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
