#include <bits/stdc++.h>
using namespace std;
using LL = long long;
const LL INF = LL(1e18);
int T, n, m;
LL a[110][110], f[110][110], g[110][110];
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]);
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) a[i][j] -= i + j;
    LL ans = INF;
    for (int p = 1; p <= n; p++)
      for (int q = 1; q <= m; q++) {
        if (a[1][1] < a[p][q] || a[n][m] < a[p][q]) continue;
        f[1][1] = a[1][1];
        for (int i = 1; i <= p; i++)
          for (int j = 1; j <= q; j++) {
            if (i == 1 && j == 1) continue;
            f[i][j] = INF;
            if (a[i][j] >= a[p][q]) {
              if (i > 1) f[i][j] = min(f[i][j], f[i - 1][j] + a[i][j]);
              if (j > 1) f[i][j] = min(f[i][j], f[i][j - 1] + a[i][j]);
            }
          }
        g[p][q] = a[p][q];
        for (int i = p; i <= n; i++)
          for (int j = q; j <= m; j++) {
            if (i == p && j == q) continue;
            g[i][j] = INF;
            if (a[i][j] >= a[p][q]) {
              if (i > p) g[i][j] = min(g[i][j], g[i - 1][j] + a[i][j]);
              if (j > q) g[i][j] = min(g[i][j], g[i][j - 1] + a[i][j]);
            }
          }
        ans = min(ans, f[p][q] + g[n][m] - a[p][q] * (n + m));
      }
    printf("%lld\n", ans);
  }
}
