#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e2 + 5;
const long long MAX_A = 1e18 + 5;
long long t, n, m, ans, tmp, a[MAX_N][MAX_N], dp[MAX_N][MAX_N];
void assignn(int i, int j) {
  if (i == 0 && j == 0) {
    return;
  }
  if (a[i][j] < a[0][0]) {
    return;
  }
  if (j) {
    dp[i][j] = min(dp[i][j - 1] + a[i][j] - a[0][0], dp[i][j]);
  }
  if (i) {
    dp[i][j] = min(dp[i - 1][j] + a[i][j] - a[0][0], dp[i][j]);
  }
}
void solve() {
  cin >> n >> m;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cin >> a[i][j];
      a[i][j] = a[i][j] - i - j;
    }
  }
  tmp = a[0][0];
  ans = LLONG_MAX;
  for (int x = 0; x < n; ++x) {
    for (int y = 0; y < m; ++y) {
      if (a[x][y] > tmp) {
        continue;
      }
      a[0][0] = a[x][y];
      for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
          dp[i][j] = MAX_A;
        }
      }
      dp[0][0] = tmp - a[0][0];
      for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
          assignn(i, j);
        }
      }
      ans = min(ans, dp[n - 1][m - 1]);
    }
  }
  cout << ans << endl;
}
int main() {
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
