#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    long long int arr[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> arr[i][j];
      }
    }
    long long int a0 = arr[0][0];
    long long int ans = 1e18;
    long long int dp[n + 1][m + 1];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        long long int need = arr[i][j] - i - j;
        if (need > a0) continue;
        for (int k = 0; k < n; k++) {
          for (int l = 0; l < m; l++) {
            dp[k][l] = 1e18;
          }
        }
        dp[0][0] = a0 - need;
        for (int k = 0; k < n; k++) {
          for (int l = 0; l < m; l++) {
            if (k == 0 && l == 0) continue;
            long long int now = need + k + l;
            if (now > arr[k][l]) continue;
            now = arr[k][l] - now;
            if (k == 0) {
              dp[k][l] = dp[k][l - 1] + now;
            } else if (l == 0) {
              dp[k][l] = dp[k - 1][l] + now;
            } else {
              dp[k][l] = min(dp[k - 1][l], dp[k][l - 1]) + now;
            }
          }
        }
        ans = min(ans, dp[n - 1][m - 1]);
      }
    }
    cout << ans << endl;
  }
}
