#include <bits/stdc++.h>
using namespace std;
const long long MAXN = (long long)((1e5) + 100);
long long gcd(long long a, long long b) {
  if (a == 0) return b;
  return gcd(b % a, a);
}
long long max(long long a, long long b) {
  if (a > b)
    return a;
  else
    return b;
}
long long min(long long a, long long b) {
  if (a < b)
    return a;
  else
    return b;
}
void pr(long long x) { cout << x; }
void prl(long long x) { cout << x << "\n"; }
long long cbrt(long long x) {
  long long lo = 1, hi = min(2000000ll, x);
  while (hi - lo > 1) {
    long long mid = (lo + hi) / 2;
    if (mid * mid * mid < x) {
      lo = mid;
    } else
      hi = mid;
  }
  if (hi * hi * hi <= x)
    return hi;
  else
    return lo;
}
const long long dx[4] = {-1, 1, 0, 0};
const long long dy[4] = {0, 0, -1, 1};
long long XX[] = {-1, -1, -1, 0, 0, 1, 1, 1};
long long YY[] = {-1, 0, 1, -1, 1, -1, 0, 1};
const long long N = (long long)(2 * 1e5 + 10);
long long a[102][102], dp[102][102];
long long n, m;
long long func(long long i, long long j, long long val) {
  if (i == (n - 1) && j == (m - 1)) {
    if (a[i][j] < val)
      return dp[i][j] = 1e18;
    else
      return dp[i][j] = (a[i][j] - val);
  }
  if (i >= n || j >= m) return 1e18;
  if (a[i][j] < val) return 1e18;
  if (dp[i][j] != -1) return dp[i][j];
  long long change = a[i][j] - val;
  return dp[i][j] =
             change + min(func(i + 1, j, val + 1), func(i, j + 1, val + 1));
}
signed main() {
  ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  long long T = 1;
  cin >> T;
  while (T--) {
    cin >> n >> m;
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        cin >> a[i][j];
      }
    }
    long long ans = 1e18;
    for (long long i = 0; i < n; i++) {
      for (long long j = 0; j < m; j++) {
        for (long long i1 = 0; i1 < n; i1++) {
          for (long long j1 = 0; j1 < m; j1++) {
            dp[i1][j1] = -1;
          }
        }
        long long firstVal = a[i][j] - (i + j);
        ans = min(ans, func(0, 0, firstVal));
      }
    }
    prl(ans);
  }
}
