#include <bits/stdc++.h>
using namespace std;
const int maxn = 200;
const long long inf = 1e18;
int T, n, m;
long long h[maxn][maxn], dp[maxn][maxn];
long long solve(long long x) {
  for (int i = 2; i <= max(n, m); ++i) dp[0][i] = dp[i][0] = inf;
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) {
      long long t = i - 1 + j - 1 + x;
      if (t > h[i][j])
        dp[i][j] = inf;
      else
        dp[i][j] = min(dp[i][j - 1], dp[i - 1][j]) + h[i][j] - t;
    }
  }
  return dp[n][m];
}
int main() {
  cin >> T;
  while (T--) {
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) {
      for (int j = 1; j <= m; ++j) {
        cin >> h[i][j];
      }
    }
    long long ans = inf;
    for (int i = 1; i <= n; ++i) {
      for (int j = 1; j <= m; ++j) {
        ans = min(min(ans, solve(h[i][j])), solve(h[i][j] - i - j + 2));
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
