#include <bits/stdc++.h>
using namespace std;
const long long INF = 2e18;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int tt;
  cin >> tt;
  while (tt--) {
    int n, m;
    cin >> n >> m;
    long long a[n][m];
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) cin >> a[i][j];
    long long ans = INF;
    for (int r = 0; r < n; r++) {
      for (int c = 0; c < m; c++) {
        vector<vector<long long>> dp(n, vector<long long>(m, INF));
        long long cur = a[r][c];
        int step = r + c;
        if (a[0][0] < cur - step) continue;
        dp[0][0] = a[0][0] - (cur - step);
        for (int i = 0; i <= r; i++) {
          for (int j = 0; j <= c; j++) {
            if (!i && !j) continue;
            if (a[i][j] >= cur - (step - i - j)) {
              long long nxt = a[i][j] - (cur - (step - i - j));
              if (i) dp[i][j] = min(dp[i][j], dp[i - 1][j]);
              if (j) dp[i][j] = min(dp[i][j], dp[i][j - 1]);
              dp[i][j] += nxt;
            }
            if (dp[i][j] > INF) dp[i][j] = INF;
          }
        }
        if (dp[r][c] == INF) continue;
        for (int i = r; i < n; i++) {
          for (int j = c; j < m; j++) {
            if (i == r && j == c) continue;
            if (a[i][j] >= cur + (i + j - step)) {
              long long nxt = a[i][j] - (cur + (i + j - step));
              if (i) dp[i][j] = min(dp[i][j], dp[i - 1][j]);
              if (j) dp[i][j] = min(dp[i][j], dp[i][j - 1]);
              dp[i][j] += nxt;
            }
            if (dp[i][j] > INF) dp[i][j] = INF;
          }
        }
        ans = min(ans, dp[n - 1][m - 1]);
      }
    }
    cout << ans << '\n';
  }
}
