#include <bits/stdc++.h>
using namespace std;
void __print(int x) { cerr << x; }
void __print(long x) { cerr << x; }
void __print(long long x) { cerr << x; }
void __print(unsigned x) { cerr << x; }
void __print(unsigned long x) { cerr << x; }
void __print(unsigned long long x) { cerr << x; }
void __print(float x) { cerr << x; }
void __print(double x) { cerr << x; }
void __print(long double x) { cerr << x; }
void __print(char x) { cerr << '\'' << x << '\''; }
void __print(const char *x) { cerr << '\"' << x << '\"'; }
void __print(const string &x) { cerr << '\"' << x << '\"'; }
void __print(bool x) { cerr << (x ? "true" : "false"); }
template <typename T, typename V>
void __print(const pair<T, V> &x) {
  cerr << '{';
  __print(x.first);
  cerr << ',';
  __print(x.second);
  cerr << '}';
}
template <typename T>
void __print(const T &x) {
  int f = 0;
  cerr << '{';
  for (auto &i : x) cerr << (f++ ? "," : ""), __print(i);
  cerr << "}";
}
void _print() { cerr << "]\n"; }
template <typename T, typename... V>
void _print(T t, V... v) {
  __print(t);
  if (sizeof...(v)) cerr << ", ";
  _print(v...);
}
void solve() {
  int n, m;
  cin >> n >> m;
  vector<vector<long long> > a(n, vector<long long>(m));
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j) cin >> a[i][j];
  long long INF = 1e18;
  long long ans = INF;
  for (int x = 0; x < n; ++x) {
    for (int y = 0; y < m; ++y) {
      long long need = a[x][y] - x - y;
      if (a[0][0] < need) continue;
      vector<vector<long long> > dp(n, vector<long long>(m, INF));
      dp[0][0] = a[0][0] - need;
      for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
          long long cur_need = need + i + j;
          if (a[i][j] < cur_need) continue;
          if (i > 0)
            dp[i][j] = min(dp[i][j], dp[i - 1][j] + a[i][j] - cur_need);
          if (j > 0)
            dp[i][j] = min(dp[i][j], dp[i][j - 1] + a[i][j] - cur_need);
        }
      }
      ans = min(ans, dp[n - 1][m - 1]);
    }
  }
  cout << ans << endl;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL), cout.tie(NULL);
  int t = 1;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
