#include <bits/stdc++.h>
using namespace std;
using gg = long long;
constexpr gg MAX = 1e2 + 5;
constexpr gg mod = 1e9 + 7;
constexpr gg INF = 4e18;
constexpr double eps = 1e-12;
gg ti, ni, mi, ki, di, pi, xi, yi;
using ag = array<gg, 4>;
gg a[MAX][MAX], dp[MAX][MAX];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> ti;
  while (ti--) {
    cin >> ni >> mi;
    set<gg> vt;
    for (gg i = (1); i <= (ni); i += (1)) {
      for (gg j = (1); j <= (mi); j += (1)) {
        cin >> a[i][j];
        if (a[i][j] - i - j + 2 <= a[1][1]) {
          vt.insert(a[i][j] - i - j + 2);
        }
      }
    }
    gg ans = INF;
    for (gg k : vt) {
      dp[1][1] = a[1][1] - k;
      for (gg i = (1); i <= (ni); i += (1)) {
        for (gg j = (1); j <= (mi); j += (1)) {
          if (i == 1 and j == 1) {
            continue;
          }
          gg t = k + i + j - 2;
          if (a[i][j] < t) {
            dp[i][j] = -1;
            continue;
          }
          t = a[i][j] - t;
          dp[i][j] = INF;
          if (i > 1 and dp[i - 1][j] >= 0) {
            dp[i][j] = min(dp[i][j], dp[i - 1][j] + t);
          }
          if (j > 1 and dp[i][j - 1] >= 0) {
            dp[i][j] = min(dp[i][j], dp[i][j - 1] + t);
          }
        }
      }
      if (dp[ni][mi] != -1) {
        ans = min(ans, dp[ni][mi]);
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
