#include <bits/stdc++.h>
using namespace std;
int32_t main() {
  long long t;
  cin >> t;
  while (t--) {
    long long n, m;
    cin >> n >> m;
    vector<vector<long long>> a(n, vector<long long>(m));
    for (long long i = 0; i < n; i++)
      for (long long j = 0; j < m; j++) cin >> a[i][j];
    long long a00 = a[0][0];
    long long need;
    long long ans = 1e18;
    for (long long r = 0; r < n; r++)
      for (long long c = 0; c < m; c++) {
        need = a[r][c] - r - c;
        if (need > a00) continue;
        a[0][0] = need;
        vector<vector<long long>> dp(n, vector<long long>(m, 1e18));
        dp[0][0] = a00 - a[0][0];
        for (long long i = 0; i < n; i++)
          for (long long j = 0; j < m; j++) {
            need = a[0][0] + i + j;
            if (need > a[i][j]) continue;
            if (i > 0) dp[i][j] = min(dp[i][j], dp[i - 1][j] + a[i][j] - need);
            if (j > 0) dp[i][j] = min(dp[i][j], dp[i][j - 1] + a[i][j] - need);
          }
        ans = min(ans, dp[n - 1][m - 1]);
      }
    cout << ans << "\n";
  }
  return 0;
}
