#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    vector<vector<ll>> a(n + 1, vector<ll>(m + 1));
    for (int i = 1; i <= n; ++i) {
      for (int j = 1; j <= m; ++j) {
        cin >> a[i][j];
      }
    }
    const ll I = 1e18;
    ll b = I;
    for (int i = 1; i <= n; ++i) {
      for (int j = 1; j <= m; ++j) {
        vector<vector<ll>> c(n + 1, vector<ll>(m + 1, I));
        c[0][1] = c[1][0] = 0;
        for (int g = 1; g <= n; ++g) {
          for (int h = 1; h <= m; ++h) {
            ll y = a[g][h] - (a[i][j] - (i - g) - (j - h));
            if (y >= 0) {
              c[g][h] = min(c[g - 1][h] + y, c[g][h - 1] + y);
            }
          }
        }
        b = min(b, c[n][m]);
      }
    }
    cout << b << endl;
  }
  return 0;
}
