#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, vector<ll>(m));
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        cin >> a[i][j];
      }
    }
    const ll I = 1e18;
    ll b = I;
    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        vector<vector<ll>> c(n, vector<ll>(m, I));
        auto z = [a](int i, int j, int g, int h) {
          if (a[g][h] >= a[i][j] - (i - g) - (j - h)) {
            return a[g][h] - (a[i][j] - (i - g) - (j - h));
          }
          return I;
        };
        c[0][0] = z(i, j, 0, 0);
        for (int g = 0; g <= i; ++g) {
          for (int h = 0; h <= j; ++h) {
            ll y = z(i, j, g, h);
            if (y != I) {
              if (g > 0 && c[g - 1][h] != I) {
                c[g][h] = c[g - 1][h] + y;
              }
              if (h > 0 && c[g][h - 1] != I) {
                c[g][h] = min(c[g][h], c[g][h - 1] + y);
              }
            }
          }
        }
        for (int g = i; g < n; ++g) {
          for (int h = j; h < m; ++h) {
            ll y = z(i, j, g, h);
            if (y != I) {
              if (g > 0 && c[g - 1][h] != I) {
                c[g][h] = c[g - 1][h] + y;
              }
              if (h > 0 && c[g][h - 1] != I) {
                c[g][h] = min(c[g][h], c[g][h - 1] + y);
              }
            }
          }
        }
        b = min(b, c[n - 1][m - 1]);
      }
    }
    cout << b << endl;
  }
  return 0;
}
