#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  long long arr[100][100];
  while (t--) {
    int n, m;
    long long first_value;
    long long ans = 1e18;
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        scanf("%lld", &arr[i][j]);
      }
    }
    first_value = arr[0][0];
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        if (arr[i][j] - (i + j) > first_value) {
          continue;
        }
        arr[0][0] = arr[i][j] - (i + j);
        vector<vector<long long>> dp(n, vector<long long>(m, 1e18));
        dp[0][0] = first_value - (arr[i][j] - (i + j));
        for (int k = 0; k < n; ++k) {
          for (int l = 0; l < m; ++l) {
            if (arr[k][l] < arr[0][0] + k + l) {
              continue;
            }
            if (k > 0) {
              dp[k][l] =
                  min(dp[k][l], dp[k - 1][l] + arr[k][l] - (arr[0][0] + k + l));
            }
            if (l > 0) {
              dp[k][l] =
                  min(dp[k][l], dp[k][l - 1] + arr[k][l] - (arr[0][0] + k + l));
            }
          }
        }
        ans = min(ans, dp[n - 1][m - 1]);
      }
    }
    cout << ans << endl;
  }
}
