#include <bits/stdc++.h>
using namespace std;
long long int a[102][102], dp[102][102];
long long int n, m;
long long int ans(long long int i, long long int j, long long int v) {
  if (i == (n - 1) and j == (m - 1)) {
    if (a[i][j] < v)
      return dp[i][j] = 1e18;
    else
      return dp[i][j] = (a[i][j] - v);
  }
  if (i >= n or j >= m) return 1e18;
  if (a[i][j] < v) return 1e18;
  if (dp[i][j] != -1) return dp[i][j];
  long long int chng = a[i][j] - v;
  return dp[i][j] = chng + min(ans(i + 1, j, v + 1), ans(i, j + 1, v + 1));
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    cin >> n >> 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 res = 1e18;
    for (long long int i = 0; i < n; i++) {
      for (long long int j = 0; j < m; j++) {
        for (long long int k = 0; k < n; k++) {
          for (long long int l = 0; l < m; l++) {
            dp[k][l] = -1;
          }
        }
        long long int tmp = a[i][j] - (i + j);
        res = min(res, ans(0, 0, tmp));
      }
    }
    cout << res << endl;
  }
  return 0;
}
