#include <bits/stdc++.h>
using namespace std;
template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  os << "{";
  for (typename vector<T>::const_iterator vi = v.begin(); vi != v.end(); ++vi) {
    if (vi != v.begin()) os << ", ";
    os << *vi;
  }
  os << "}";
  return os;
}
template <typename A, typename B>
ostream &operator<<(ostream &os, const pair<A, B> &p) {
  os << '(' << p.first << ", " << p.second << ')';
  return os;
}
long long T, N, M, K;
long long v[110][110];
long long dp[110][110];
long long solve(int i, int j, long long valor) {
  if (v[i][j] < valor) return 0x3f3f3f3f3f3f3f3f;
  if (i == N - 1 && j == M - 1) return dp[i][j] = v[i][j] - valor;
  if (dp[i][j] == -1) {
    long long ans = 0x3f3f3f3f3f3f3f3f;
    if (j < M - 1)
      ans = min(ans, v[i][j] - valor + solve(i, j + 1, valor + 1LL));
    if (i < N - 1)
      ans = min(ans, v[i][j] - valor + solve(i + 1, j, valor + 1LL));
    dp[i][j] = ans;
  }
  return dp[i][j];
}
void solve() {
  long long ans = 0x3f3f3f3f3f3f3f3f;
  for (int i = (int)(0); (i) < int(N); (i)++) {
    for (int j = (int)(0); (j) < int(M); (j)++) {
      memset(dp, -1, sizeof(dp));
      long long aux = v[i][j] - i - j;
      ans = min(ans, solve(0, 0, aux));
    }
  }
  cout << ans << "\n";
}
int main() {
  cin >> T;
  while (T--) {
    cin >> N >> M;
    for (int i = (int)(0); (i) < int(N); (i)++)
      for (int j = (int)(0); (j) < int(M); (j)++) cin >> v[i][j];
    solve();
  }
  return 0;
}
