#include <bits/stdc++.h>
using namespace std;
long long a[105][105], v[105][105], dp[105][105];
long long slove(int x, int y, int n, int m) {
  long long t = a[x][y] - (x + y - 2);
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      v[i][j] = a[i][j] - (t + i + j - 2);
    }
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      dp[i][j] = -1;
      if (v[i][j] < 0) continue;
      if (i == 1 && j == 1)
        dp[i][j] = v[i][j];
      else if (i == 1) {
        long long t = dp[i][j - 1];
        if (t != -1) dp[i][j] = t + v[i][j];
      } else if (j == 1) {
        long long t = dp[i - 1][j];
        if (t != -1) dp[i][j] = t + v[i][j];
      } else {
        long long t1 = dp[i - 1][j], t2 = dp[i][j - 1];
        if (t1 != -1) dp[i][j] = t1 + v[i][j];
        if (t2 != -1) {
          if (dp[i][j] == -1)
            dp[i][j] = t2 + v[i][j];
          else
            dp[i][j] = min(dp[i][j], t2 + v[i][j]);
        }
      }
    }
  }
  if (dp[n][m] != -1)
    return dp[n][m];
  else
    return 1e18;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        cin >> a[i][j];
      }
    }
    long long ans = 1e18;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        ans = min(ans, slove(i, j, n, m));
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
