#include <bits/stdc++.h>
using namespace std;
const int N = 1e2 + 5e1;
long long a[N][N], Memo[N][N];
int Tc, n, m;
inline bool isValid(int i, int j) { return i < n && j < m; }
long long calc(int i, int j, long long h) {
  if (i == n - 1 && j == m - 1 && a[i][j] >= h) return a[i][j] - h;
  long long &re = Memo[i][j];
  if (re != -1) return re;
  long long c1 = (isValid(i + 1, j) && a[i][j] >= h)
                     ? calc(i + 1, j, h + 1) + a[i][j] - h
                     : 4e18;
  long long c2 = (isValid(i, j + 1) && a[i][j] >= h)
                     ? calc(i, j + 1, h + 1) + a[i][j] - h
                     : 4e18;
  return re = min(c1, c2);
}
int main() {
  cin >> Tc;
  while (Tc--) {
    cin >> n >> m;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) cin >> a[i][j];
    long long Ans = 4e18;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
        memset(Memo, -1, sizeof Memo),
            Ans = min(Ans, calc(0, 0, a[i][j] - (i + j)));
    cout << Ans << endl;
  }
  return 0;
}
