#include <bits/stdc++.h>
using namespace std;
long long int mxn = 1e18;
long long int arr[102][102];
pair<long long int, long long int> dp[102][102];
int main() {
  int T;
  scanf("%d", &T);
  while (T--) {
    long long int ans = mxn;
    int n, m;
    cin >> n >> m;
    vector<long long int> V;
    set<long long int> S;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        cin >> arr[i][j];
        long long int x = arr[i][j] - (long long int)((i - 1) + (j - 1));
        if (x > arr[1][1]) continue;
        S.insert(x);
      }
    }
    for (auto i : S) V.push_back(i);
    long long int Exact = arr[1][1];
    int sz = V.size();
    for (int k = 0; k < sz; k++) {
      arr[1][1] = V[k];
      memset(dp, -1, sizeof dp);
      for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
          if (i == 1 && j == 1) {
            dp[i][j].first = arr[i][j];
            dp[i][j].second = 0;
          } else if (i == 1) {
            dp[i][j].first = dp[i][j - 1].first + 1;
            if (dp[i][j - 1].second == -1) {
              dp[i][j].second = -1;
              continue;
            }
            if (dp[i][j].first > arr[i][j])
              dp[i][j].second = -1;
            else
              dp[i][j].second =
                  arr[i][j] - dp[i][j].first + dp[i][j - 1].second;
          } else if (j == 1) {
            dp[i][j].first = dp[i - 1][j].first + 1;
            if (dp[i - 1][j].second == -1) {
              dp[i][j].second = -1;
              continue;
            }
            if (dp[i][j].first > arr[i][j])
              dp[i][j].second = -1;
            else
              dp[i][j].second =
                  arr[i][j] - dp[i][j].first + dp[i - 1][j].second;
          } else {
            dp[i][j].first = dp[i - 1][j].first + 1;
            if (dp[i][j].first > arr[i][j])
              dp[i][j].second = -1;
            else if (dp[i - 1][j].second == -1 && dp[i][j - 1].second == -1)
              dp[i][j].second = -1;
            else if (dp[i - 1][j].second == -1)
              dp[i][j].second =
                  arr[i][j] - dp[i][j].first + dp[i][j - 1].second;
            else if (dp[i][j - 1].second == -1)
              dp[i][j].second =
                  arr[i][j] - dp[i][j].first + dp[i - 1][j].second;
            else
              dp[i][j].second = min(dp[i - 1][j].second, dp[i][j - 1].second) +
                                arr[i][j] - dp[i][j].first;
          }
        }
      }
      if (dp[n][m].second != -1)
        ans = min(ans, dp[n][m].second + Exact - arr[1][1]);
    }
    printf("%lld\n", ans);
  }
}
