#include <bits/stdc++.h>
using namespace std;
long long dp[102][102], mat[102][102], inf = 1e18 + 10;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  for (int k = 0; k < t; k++) {
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        dp[i][j] = inf;
        cin >> mat[i][j];
      }
    }
    long long ini = mat[0][0], ans = inf;
    for (int l = 0; l < n; l++) {
      for (int q = 0; q < m; q++) {
        mat[0][0] = mat[l][q] - l - q;
        if (mat[0][0] > ini) continue;
        dp[0][0] = 0;
        for (int i = 0; i < n; i++) {
          for (int j = 0; j < m; j++) {
            if (i == 0 && j == 0) continue;
            dp[i][j] = inf;
            if (i > 0 && mat[i][j] >= mat[0][0] + i + j)
              dp[i][j] =
                  min(dp[i - 1][j] + mat[i][j] - mat[0][0] - i - j, dp[i][j]);
            if (j > 0 && mat[i][j] >= mat[0][0] + j + i)
              dp[i][j] =
                  min(dp[i][j - 1] + mat[i][j] - mat[0][0] - i - j, dp[i][j]);
          }
        }
        ans = min(ans, dp[n - 1][m - 1] + (ini - mat[0][0]));
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
