#include <bits/stdc++.h>
using namespace std;
long long int mod = 1000000007;
long long int z = 1000000000;
const long long int N = 1e5 + 1;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  long long int t;
  cin >> t;
  while (t--) {
    long long int n, m;
    cin >> n >> m;
    vector<vector<long long int>> a(n, vector<long long int>(m));
    for (long long int i = 0; i < n; i++) {
      for (long long int j = 0; j < m; j++) {
        cin >> a[i][j];
      }
    }
    long long int target = a[0][0];
    long long int ans = 1e18;
    for (long long int i = 0; i < n; i++) {
      for (long long int j = 0; j < m; j++) {
        long long int posn = a[i][j] - i - j;
        if (a[0][0] < posn) continue;
        vector<vector<long long int>> dp(n, vector<long long int>(m, 1e18));
        dp[0][0] = a[0][0] - posn;
        for (long long int k = 0; k < n; k++) {
          for (long long int l = 0; l < m; l++) {
            if (a[k][l] >= posn + k + l) {
              if (l > 0)
                dp[k][l] =
                    min(dp[k][l], dp[k][l - 1] + (a[k][l] - (posn + k + l)));
              if (k > 0)
                dp[k][l] =
                    min(dp[k][l], dp[k - 1][l] + (a[k][l] - (posn + k + l)));
            }
          }
        }
        ans = min(ans, dp[n - 1][m - 1]);
      }
    }
    cout << ans << endl;
  }
  return 0;
}
