#include <bits/stdc++.h>
using namespace std;
long long int a[101][101];
long long int dp[101][101];
long long int orig;
int n, m;
void com() {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (i == 0 && j == 0) {
        dp[i][j] = orig - a[0][0];
        continue;
      }
      if (a[i][j] < (a[0][0] + i + j)) {
        dp[i][j] = -2;
      } else {
        dp[i][j] = 1000000000000000000;
        if (j > 0 && dp[i][j - 1] != -2) {
          dp[i][j] = min(dp[i][j], dp[i][j - 1] + a[i][j] - (a[0][0] + i + j));
        }
        if (i > 0 && dp[i - 1][j] != -2) {
          dp[i][j] = min(dp[i][j], dp[i - 1][j] + a[i][j] - (a[0][0] + i + j));
        }
        if (dp[i][j] == 1000000000000000000) {
          dp[i][j] = -2;
        }
      }
    }
  }
}
int main() {
  int t;
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; j++) {
        cin >> a[i][j];
      }
    }
    long long int ans = 1000000000000000000;
    orig = a[0][0];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        a[0][0] = a[i][j] - i - j;
        if (a[0][0] > orig) continue;
        com();
        if (dp[n - 1][m - 1] != -2) {
          ans = min(ans, dp[n - 1][m - 1]);
        }
        a[0][0] = orig;
      }
    }
    cout << ans << "\n";
  }
}
