#include <bits/stdc++.h>
using namespace std;
const int N = 1e2 + 10;
const long long INF = 1e18;
int n, m;
long long a[N][N], f[N][N];
long long calc(long long num) {
  for (int i = 0; i <= n; i++)
    for (int j = 0; j <= m; j++) f[i][j] = INF;
  f[0][0] = f[0][1] = f[1][0] = 0;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      long long cost = a[i][j] - (num + i + j - 2);
      if (cost < 0) continue;
      f[i][j] = min(f[i - 1][j], f[i][j - 1]) + cost;
    }
  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 mx = a[n][m] - n - m + 2, ans = 9e18;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) {
        long long num = a[i][j] - i - j + 2;
        if (num > mx) continue;
        ans = min(ans, calc(num));
      }
    printf("%lld\n", ans);
  }
  return 0;
}
