#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    long long in[n][m], dp[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> in[i][j];
      }
    }
    long long ans = 1e18;
    for (int x = 0; x < n; x++) {
      for (int y = 0; y < m; y++) {
        long long need = in[x][y] - x - y;
        if (need > in[0][0]) {
          continue;
        }
        for (int i = 0; i < n; i++) {
          for (int j = 0; j < m; j++) {
            dp[i][j] = 1e18;
          }
        }
        dp[0][0] = in[0][0] - need;
        for (int i = 0; i < n; i++) {
          for (int j = 0; j < m; j++) {
            long long needn = in[i][j] - (need + i + j);
            if (needn < 0) {
              continue;
            }
            if (i > 0) {
              dp[i][j] = min(dp[i][j], dp[i - 1][j] + needn);
            }
            if (j > 0) {
              dp[i][j] = min(dp[i][j], dp[i][j - 1] + needn);
            }
          }
        }
        ans = min(ans, dp[n - 1][m - 1]);
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
