#include <bits/stdc++.h>
using namespace std;
long long n, m, a[105][105], x, y, memo[105][105], inf = 1000000000000000000;
long long dp(long long r, long long c) {
  long long ret = inf, z;
  if ((r == n - 1) && (c == m - 1)) return 0;
  if (memo[r][c] != -1) return memo[r][c];
  z = (x + y) - (r + c + 1);
  if (r < n - 1)
    if (a[r + 1][c] >= a[x][y] - z)
      ret = min(ret, dp(r + 1, c) + a[r + 1][c] - a[x][y] + z);
  if (c < m - 1)
    if (a[r][c + 1] >= a[x][y] - z)
      ret = min(ret, dp(r, c + 1) + a[r][c + 1] - a[x][y] + z);
  memo[r][c] = ret;
  return ret;
}
int main() {
  long long tc, z, ans;
  scanf("%lld", &tc);
  while (tc--) {
    scanf("%lld %lld", &n, &m);
    for (long long i = 0; i < n; i++)
      for (long long j = 0; j < m; j++) scanf("%lld", &a[i][j]);
    ans = inf;
    for (x = 0; x < n; x++)
      for (y = 0; y < m; y++) {
        z = x + y;
        if (a[0][0] < a[x][y] - z) continue;
        for (long long i = 0; i < n; i++)
          for (long long j = 0; j < m; j++) memo[i][j] = -1;
        ans = min(ans, dp(0, 0) + a[0][0] - a[x][y] + z);
      }
    printf("%lld\n", ans);
  }
  return 0;
}
