#include <bits/stdc++.h>
using namespace std;
template <class T>
void read(T& x) {
  T res = 0, f = 1;
  char c = getchar();
  while (!isdigit(c)) {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (isdigit(c)) {
    res = (res << 3) + (res << 1) + c - '0';
    c = getchar();
  }
  x = res * f;
}
const long long N = 100 + 10;
long long t, a[N][N], n, m, b[N][N], dp[N][N], inf = 0x3f3f3f3f3f3f3f3f;
long long check(long long x) {
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      b[i][j] = a[i][j] - (x + (i + j - 2));
    }
  memset(dp, 0x3f, sizeof(dp));
  dp[1][1] = b[1][1];
  if (dp[1][1] < 0) return dp[0][0];
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      if (i == 1 && j == 1 || b[i][j] < 0) continue;
      if (b[i][j - 1] >= 0) dp[i][j] = min(dp[i][j], dp[i][j - 1] + b[i][j]);
      if (b[i - 1][j] >= 0) dp[i][j] = min(dp[i][j], dp[i - 1][j] + b[i][j]);
    }
  return dp[n][m];
}
int main() {
  read(t);
  while (t--) {
    read(n), read(m);
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) {
        read(a[i][j]);
      }
    long long ans = 4e18;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) {
        if (a[i][j] - (i + j - 2) > a[1][1]) continue;
        ans = min(ans, check(a[i][j] - (i + j - 2)));
      }
    printf("%lld\n", ans);
  }
  return 0;
}
