#include <bits/stdc++.h>
using namespace std;
const int maxn = 105;
const int inf = 0x3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
long long a[maxn][maxn];
long long op[maxn][maxn];
long long f[maxn][maxn];
int n, m;
long long cal(long long mid) {
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      f[i][j] = INF;
      op[i][j] = a[i][j] - (i + j - 2 + mid);
    }
  }
  f[1][1] = op[1][1];
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (op[i][j] < 0) continue;
      if (j > 1) {
        f[i][j] = min(f[i][j], f[i][j - 1] + op[i][j]);
      }
      if (i > 1) {
        f[i][j] = min(f[i][j], f[i - 1][j] + op[i][j]);
      }
    }
  }
  return f[n][m];
}
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        scanf("%lld", a[i] + j);
      }
    }
    long long ans = INF;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        long long src = a[i][j] + 2 - i - j;
        if (src > a[1][1]) continue;
        ans = min(ans, cal(src));
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
