#include <bits/stdc++.h>
using namespace std;
int64_t a[100][100], b[100][100], mx = 1e18;
int m, n;
int64_t solve() {
  for (int i = 1; i < m; ++i) b[i][0] = min(mx, b[i][0] + b[i - 1][0]);
  for (int j = 1; j < n; ++j) b[0][j] = min(mx, b[0][j] + b[0][j - 1]);
  for (int i = 1; i < m; ++i) {
    for (int j = 1; j < n; ++j) {
      b[i][j] += min(b[i - 1][j], b[i][j - 1]);
      if (b[i][j] > mx) b[i][j] = mx;
    }
  }
  return b[m - 1][n - 1];
}
int main() {
  ios::sync_with_stdio(false);
  int t;
  int64_t ans;
  cin >> t;
  while (t--) {
    ans = 1e18;
    cin >> m >> n;
    for (int i = 0; i < m; ++i) {
      for (int j = 0; j < n; ++j) {
        cin >> a[i][j];
        a[i][j] -= i + j;
      }
    }
    for (int i = 0; i < m; ++i) {
      for (int j = 0; j < n; ++j) {
        int64_t base = a[i][j];
        for (int x = 0; x < m; ++x) {
          for (int y = 0; y < n; ++y) {
            b[x][y] = a[x][y] - base;
            if (b[x][y] < 0) b[x][y] = 1e18;
          }
        }
        ans = min(ans, solve());
      }
    }
    cout << ans << endl;
  }
}
