#include <bits/stdc++.h>
using namespace std;
long long n, m, a[110][110], dp[110][110];
bool vis[110][110];
long long dfs(long long x, long long y, long long num) {
  if (a[x][y] < num) return (long long)3000000000000000000;
  if (x == n - 1 && y == m - 1) return a[x][y] - num;
  if (dp[x][y] != -1) return dp[x][y];
  long long ret = (long long)3000000000000000000;
  if (y + 1 < m) {
    ret = min(ret, dfs(x, y + 1, num + 1));
  }
  if (x + 1 < n) {
    ret = min(ret, dfs(x + 1, y, num + 1));
  }
  return dp[x][y] = min((long long)3000000000000000000, ret + a[x][y] - num);
}
long long solve() {
  long long ans = (long long)3000000000000000000;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (a[i][j] - i - j <= a[0][0]) {
        memset(dp, -1, sizeof dp);
        ans = min(ans, dfs(0, 0, a[i][j] - i - j));
      }
    }
  }
  return ans;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    cin >> n >> m;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        cin >> a[i][j];
      }
    }
    cout << solve() << '\n';
  }
}
