#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using vb = vector<bool>;
using vvi = vector<vi>;
using vvl = vector<vl>;
using vvb = vector<vb>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
const ll INF = 4e18;
int main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  int T = 1;
  cin >> T;
  while (T--) {
    int rows, cols;
    cin >> rows >> cols;
    vvl a(rows, vl(cols));
    vvl dp(rows, vl(cols, INF));
    auto findMinMoves = [&](ll reqInitH) -> ll {
      if (a[0][0] < reqInitH) return INF;
      dp[0][0] = a[0][0] - reqInitH;
      ll reqH, reqMoves;
      for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
          if (row == 0 and col == 0) continue;
          dp[row][col] = INF;
          reqH = reqInitH + ll(row + col);
          reqMoves = a[row][col] - reqH;
          if (reqMoves < 0) {
            continue;
          }
          if (row - 1 >= 0) {
            if (dp[row - 1][col] != INF) {
              dp[row][col] = min(dp[row][col], dp[row - 1][col] + reqMoves);
            }
          }
          if (col - 1 >= 0) {
            if (dp[row][col - 1] != INF) {
              dp[row][col] = min(dp[row][col], dp[row][col - 1] + reqMoves);
            }
          }
        }
      }
      return dp[rows - 1][cols - 1];
    };
    for (int row = 0; row < rows; row++) {
      for (int col = 0; col < cols; col++) {
        cin >> a[row][col];
      }
    }
    ll minMoves = LLONG_MAX;
    for (int row = 0; row < rows; row++) {
      for (int col = 0; col < cols; col++) {
        ll reqInitH = a[row][col] - (row + col);
        minMoves = min(minMoves, findMinMoves(reqInitH));
      }
    }
    cout << minMoves << "\n";
  }
}
