#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
const long long MOD = 1000000007;
long long tab[101][101], dp[101][101];
long long n, m;
long long solve(long long ai, long long aj, long long bi, long long bj,
                bool f) {
  long long a, b;
  if (f)
    a = bi, b = bj;
  else
    a = ai, b = aj;
  for (long long i = ai; i <= bi; ++i)
    for (long long j = aj; j <= bj; ++j) {
      long long val;
      dp[i][j] = (long long)1e18;
      if (f)
        val = tab[a][b] - (a - i) - (b - j);
      else
        val = tab[a][b] + (i - a) + (j - b);
      if (val <= tab[i][j]) {
        if (i == ai && j == aj) dp[i][j] = tab[i][j] - val;
        if ((i != ai) && (dp[i - 1][j] != (long long)1e18)) {
          dp[i][j] = min(dp[i][j], dp[i - 1][j] + tab[i][j] - val);
        }
        if ((j != aj) && (dp[i][j - 1] != (long long)1e18)) {
          dp[i][j] = min(dp[i][j], dp[i][j - 1] + tab[i][j] - val);
        }
      }
    }
  return dp[bi][bj];
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long t;
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (long long i = 0; i < n; ++i)
      for (long long j = 0; j < m; ++j) cin >> tab[i][j];
    long long ans = (long long)1e18;
    for (long long i = 0; i < n; ++i)
      for (long long j = 0; j < m; ++j)
        ans = min(ans, solve(0, 0, i, j, 1) + solve(i, j, n - 1, m - 1, 0));
    cout << ans << "\n";
  }
  return 0;
}
