#include <bits/stdc++.h>
using namespace std;
template <typename T>
using v2 = vector<vector<T>>;
template <typename T>
using v3 = vector<vector<vector<T>>>;
template <class T>
istream &operator>>(istream &is, vector<T> &v) {
  for (auto &elemnt : v) is >> elemnt;
  return is;
}
template <class T, class U>
istream &operator>>(istream &is, pair<T, U> &p) {
  is >> p.first >> p.second;
  return is;
}
template <class T>
bool chmax(T &a, const T &b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
bool chmin(T &a, const T &b) {
  if (b < a) {
    a = b;
    return 1;
  }
  return 0;
}
const int MOD = 1e9 + 7;
const int INF = numeric_limits<int>::max() - (int)1e8;
const long long INFLL = numeric_limits<long long>::max() - (long long)1e17;
void solve() {
  const unsigned long long INFULL =
      numeric_limits<unsigned long long>::max() - 6e18;
  int N, M;
  cin >> N >> M;
  vector<vector<long long>> height(N, vector<long long>(M));
  for (int i = 0; i < N; i++)
    for (int j = 0; j < M; j++) cin >> height[i][j];
  auto calc = [&](long long start) {
    if (height[0][0] < start) return INFULL;
    vector<vector<unsigned long long>> dp(
        N, vector<unsigned long long>(M, INFULL));
    dp[0][0] = height[0][0] - start;
    for (long long i = 0; i < N; i++) {
      for (long long j = 0; j < M; j++) {
        long long plus = i + j;
        if (height[i][j] < (start + plus)) continue;
        unsigned long long dif = height[i][j] - (start + plus);
        if (i > 0) chmin(dp[i][j], dp[i - 1][j] + dif);
        if (j > 0) chmin(dp[i][j], dp[i][j - 1] + dif);
      }
    }
    return dp[N - 1][M - 1];
  };
  vector<long long> explore;
  for (int i = 0; i < N; i++)
    for (int j = 0; j < M; j++) {
      explore.push_back(height[i][j] - (i + j));
    }
  unsigned long long ans = INFULL;
  for (auto temp : explore) chmin(ans, calc(temp));
  for (long long i = -1e4; i <= 0; i++) chmin(ans, calc(i));
  cout << ans << endl;
}
int main() {
  int t;
  cin >> t;
  for (int i = 0; i < t; i++) solve();
}
