#include <bits/stdc++.h>
using namespace std;
long long int cost(long long int cnt, long long int curr, long long int prev) {
  if (curr <= prev) {
    return (prev - curr + 1) * cnt;
  } else {
    return curr - prev - 1;
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t, n, m, ans;
  cin >> t;
  while (t--) {
    cin >> n >> m;
    long long int a[n + 1][m + 1], dp[n + 1][m + 1], ne, ans = INT64_MAX;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) cin >> a[i][j];
    for (int N = 1; N <= n; N++)
      for (int M = 1; M <= m; M++) {
        for (int i = 0; i <= n; i++)
          for (int j = 0; j <= m; j++) dp[i][j] = INT64_MAX;
        dp[0][1] = 0;
        for (int i = 1; i <= n; i++) {
          for (int j = 1; j <= m; j++) {
            ne = a[N][M] + i - N + j - M;
            if (ne <= a[i][j] &&
                (dp[i - 1][j] != INT64_MAX || dp[i][j - 1] != INT64_MAX)) {
              dp[i][j] = ((dp[i - 1][j] < dp[i][j - 1]) ? dp[i - 1][j]
                                                        : dp[i][j - 1]) +
                         a[i][j] - ne;
            }
          }
        }
        if (ans > dp[n][m]) ans = dp[n][m];
      }
    cout << ans << endl;
  }
}
