#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 105;
const int mod = 998244353;
const double Pi = acos(-1.0);
const long long INF = 1e18;
const int G = 3, Gi = 332748118;
long long qpow(long long a, long long b) {
  long long res = 1;
  while (b) {
    if (b) res = (res * a) % mod;
    a = (a * a) % mod;
    b >>= 1;
  }
  return res;
}
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
int T, n, m;
long long dp[105][105], a[105][105];
int main() {
  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 res = INF;
    for (int x = 1; x <= n; ++x) {
      for (int y = 1; y <= m; ++y) {
        for (int i = 0; i <= n; ++i)
          for (int j = 0; j <= m; ++j) dp[i][j] = INF;
        dp[1][0] = 0;
        for (int i = 1; i <= n; ++i) {
          for (int j = 1; j <= m; ++j) {
            long long dis = abs(x - i) + abs(y - j);
            if (i <= x && j <= y && a[i][j] >= a[x][y] - dis) {
              dp[i][j] =
                  min(dp[i - 1][j], dp[i][j - 1]) + a[i][j] - (a[x][y] - dis);
            }
            if (i >= x && j >= y && a[i][j] >= a[x][y] + dis) {
              dp[i][j] =
                  min(dp[i - 1][j], dp[i][j - 1]) + a[i][j] - (a[x][y] + dis);
            }
          }
        }
        res = min(res, dp[n][m]);
      }
    }
    printf("%lld\n", res);
  }
  return 0;
}
