#include <bits/stdc++.h>
using namespace std;
const long double PI = acos(-1.0);
long long a[105][105];
long long dp[105][105][2];
void solve() {
  long long n, m;
  cin >> n >> m;
  for (long long i = 0; i < n; ++i) {
    for (long long j = 0; j < m; ++j) {
      cin >> a[i][j];
      a[i][j] -= (i + j);
    }
  }
  long long ans = 4e18;
  for (long long i = 0; i < n; ++i) {
    for (long long j = 0; j < m; ++j) {
      long long mn = a[i][j];
      for (long long i = 0; i < n; ++i) {
        for (long long j = 0; j < m; ++j) {
          for (long long k = 0; k < 2; ++k) {
            dp[i][j][k] = 4e18;
          }
        }
      }
      if (a[0][0] >= mn) {
        dp[0][0][0] = a[0][0];
      }
      if (a[n - 1][m - 1] >= mn) {
        dp[n - 1][m - 1][1] = a[n - 1][m - 1];
      }
      for (long long i = 0; i < n; ++i) {
        for (long long j = 0; j < m; ++j) {
          if (i + j == 0) continue;
          if (a[i][j] < mn) {
            continue;
          }
          if (i) {
            dp[i][j][0] = min(dp[i][j][0], dp[i - 1][j][0] + a[i][j]);
          }
          if (j) {
            dp[i][j][0] = min(dp[i][j][0], dp[i][j - 1][0] + a[i][j]);
          }
        }
      }
      for (long long i = n - 1; i >= 0; --i) {
        for (long long j = m - 1; j >= 0; --j) {
          if (i + j == n + m - 2) {
            continue;
          }
          if (a[i][j] < mn) {
            continue;
          }
          if (i != n - 1) {
            dp[i][j][1] = min(dp[i][j][1], dp[i + 1][j][1] + a[i][j]);
          }
          if (j != m - 1) {
            dp[i][j][1] = min(dp[i][j][1], dp[i][j + 1][1] + a[i][j]);
          }
        }
      }
      ans = min(ans, dp[i][j][1] + dp[i][j][0] - (n + m) * mn);
    }
  }
  cout << ans << '\n';
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
