#include <bits/stdc++.h>
using namespace std;
void vin(vector<long long int> &v, long long int t) {
  for (long long int i = 0; i < t; i++) cin >> v[i];
}
void vout(vector<long long int> &v, long long int t) {
  for (long long int i = 0; i < t; i++) cout << v[i] << " ";
  cout << endl;
}
void ingraph(vector<vector<long long int>> &graph, long long int m) {
  long long int x, y;
  for (long long int i = 0; i < m; i++) {
    cin >> x >> y;
    x--, y--;
    graph[x].push_back(y);
    graph[y].push_back(x);
  }
}
bool sortbysec(const pair<int, int> &a, const pair<int, int> &b) {
  return (a.second < b.second);
}
long long int gcd(long long int a, long long int b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
long long int lcm(long long int a, long long int b) {
  return a * b / gcd(a, b);
}
void solve() {
  long long int n, m;
  cin >> n >> m;
  vector<vector<long long int>> a(n, vector<long long int>(m)),
      dp(n, vector<long long int>(m));
  for (long long int i = 0; i < n; i++) {
    for (long long int j = 0; j < m; j++) cin >> a[i][j];
  }
  long long int ans = (long long int)1e18;
  for (long long int i = 0; i < n; i++) {
    for (long long int j = 0; j < m; j++) {
      long long int b = a[i][j] - i - j;
      if (a[0][0] < b) continue;
      vector<vector<long long int>> dp(
          n, vector<long long int>(m, (long long int)1e18));
      dp[0][0] = a[0][0] - b;
      for (long long int p = 0; p < n; p++) {
        for (long long int q = 0; q < m; q++) {
          if (a[p][q] < (b + p + q)) continue;
          if (p > 0)
            dp[p][q] = min(dp[p][q], dp[p - 1][q] + a[p][q] - (b + q + p));
          if (q > 0)
            dp[p][q] = min(dp[p][q], dp[p][q - 1] + a[p][q] - (b + q + p));
        }
      }
      ans = min(ans, dp[n - 1][m - 1]);
    }
  }
  cout << ans << "\n";
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long int t;
  cin >> t;
  while (t--) solve();
  return 0;
}
