#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 50;
long long a[110][110], dp[110][110], c[110][110];
long long b[10010];
map<long long, int> mp;
int n, m;
void cal(long long x) {
  for (int i = 0; i <= n; i++)
    for (int j = 0; j <= m; j++) dp[i][j] = 1e18;
  dp[0][1] = 0;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (c[i][j] < x) continue;
      long long now = x + i + j - 2;
      dp[i][j] =
          min(min(dp[i - 1][j], dp[i][j - 1]) + (a[i][j] - now), dp[i][j]);
    }
  }
}
void solve() {
  mp.clear();
  scanf("%d%d", &n, &m);
  int cnt = 0;
  long long ans = 1e18;
  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++) {
      c[i][j] = (a[i][j] - i - j + 2);
      if (!mp.count(c[i][j])) b[++cnt] = c[i][j];
    }
  for (int i = 1; i <= cnt; i++) {
    cal(b[i]);
    ans = min(ans, dp[n][m]);
  }
  printf("%lld\n", ans);
}
int main() {
  int t;
  scanf("%d", &t);
  while (t--) solve();
}
