#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  long long ans, gcd, masks, mask, i, h, ma, d, l, r, j, n, m, k, x, y, z, root,
      t, sum, size, p, ind, start, ans1, te, t1, t2, mid;
  cin >> t;
  while (t--) {
    cin >> n >> m;
    long long a[n][m];
    for (i = 0; i < n; i++)
      for (j = 0; j < m; j++) cin >> a[i][j];
    ans = 2 * 1e18;
    for (i = 0; i < n; i++)
      for (j = 0; j < m; j++) {
        p = a[i][j] - i - j;
        long long dp[n][m];
        for (x = 0; x < n; x++)
          for (y = 0; y < m; y++)
            if (a[x][y] < p + x + y)
              dp[x][y] = 2 * 1e18;
            else {
              if (x == 0 && y == 0)
                dp[x][y] = (a[x][y] - p - x - y);
              else if (x == 0)
                dp[x][y] = dp[x][y - 1] + (a[x][y] - p - x - y);
              else if (y == 0)
                dp[x][y] = dp[x - 1][y] + (a[x][y] - p - x - y);
              else
                dp[x][y] =
                    min(dp[x - 1][y], dp[x][y - 1]) + (a[x][y] - p - x - y);
            }
        ans = min(ans, dp[n - 1][m - 1]);
      }
    cout << ans << "\n";
  }
  return 0;
}
