#include <bits/stdc++.h>
using namespace std;
long long a[102][102], DP[102][102];
long long calc(int i, int j, int x, int y, long long val) {
  long long ans = a[x][y] - (val - i - j + x + y);
  if (ans < 0) return 1e18;
  return ans;
}
void solve() {
  int n, m;
  cin >> n >> m;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) cin >> a[i][j];
  long long ans = 1e18;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      memset(DP, 0, sizeof DP);
      long long val = a[i][j];
      for (int k = 0; k < n; k++) {
        for (int l = 0; l < m; l++) {
          if (k == 0 && l == 0) {
            DP[k][l] = calc(i, j, k, l, val);
            continue;
          }
          long long value = 1e18;
          if (k > 0) value = min(value, DP[k - 1][l]);
          if (l > 0) value = min(value, DP[k][l - 1]);
          DP[k][l] = min((long long)1e18, value + calc(i, j, k, l, val));
        }
      }
      ans = min(ans, min((long long)1e18, DP[n - 1][m - 1]));
    }
  }
  cout << ans << "\n";
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int t;
  cin >> t;
  for (int i = 0; i < t; i++) solve();
  return 0;
}
