#include <bits/stdc++.h>
using namespace std;
const int NMAX = 105;
const long long INF = (1LL << 60);
int N, M;
long long a[NMAX][NMAX];
long long dp[NMAX][NMAX];
long long Solve(long long start) {
  for (int i = 0; i <= N; ++i)
    for (int j = 0; j <= M; ++j) dp[i][j] = INF;
  dp[0][1] = dp[1][0] = 0;
  for (int i = 1; i <= N; ++i)
    for (int j = 1; j <= M; ++j) {
      long long val = a[i][j] - start - i - j + 2;
      if (val >= 0) {
        if (dp[i - 1][j] != INF) dp[i][j] = min(dp[i][j], dp[i - 1][j] + val);
        if (dp[i][j - 1] != INF) dp[i][j] = min(dp[i][j], dp[i][j - 1] + val);
      }
    }
  return dp[N][M];
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int tests;
  cin >> tests;
  while (tests-- > 0) {
    cin >> N >> M;
    for (int i = 1; i <= N; ++i)
      for (int j = 1; j <= M; ++j) cin >> a[i][j];
    long long answer = INF;
    for (int i = 1; i <= N; ++i)
      for (int j = 1; j <= M; ++j)
        answer = min(answer, Solve(a[i][j] - i - j + 2));
    cout << answer << "\n";
  }
  return 0;
}
