#include <bits/stdc++.h>
const int N = 107, inf = 0x3f3f3f3f;
using namespace std;
long long mat[N][N];
long long memo1[N][N];
int vis1[N][N];
long long memo2[N][N];
int vis2[N][N];
int caso1, caso2;
int n, m;
int p, q;
long long solve1(int i, int j) {
  int move = p - i + q - j;
  long long w = mat[i][j] - (mat[p][q] - move);
  if (w < 0) return 1e18;
  if (i == 1 and j == 1) return w;
  int& v = vis1[i][j];
  long long& st = memo1[i][j];
  if (v < caso1) {
    st = 1e18;
    if (i - 1 >= 0) {
      st = min(st, solve1(i - 1, j) + w);
    }
    if (j - 1 >= 0) {
      st = min(st, solve1(i, j - 1) + w);
    }
  }
  v = caso1;
  return st;
}
long long solve2(int i, int j) {
  int move = i - p + j - q;
  long long w = mat[i][j] - (mat[p][q] + move);
  if (w < 0) return 1e18;
  if (i == n and j == m) return w;
  int& v = vis2[i][j];
  long long& st = memo2[i][j];
  if (v < caso2) {
    st = 1e18;
    if (i + 1 <= n) {
      st = min(st, solve2(i + 1, j) + w);
    }
    if (j + 1 <= m) {
      st = min(st, solve2(i, j + 1) + w);
    }
  }
  v = caso2;
  return st;
}
void _solve() {
  cin >> n >> m;
  vector<long long> vec;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> mat[i][j];
    }
  }
  long long ans = 1e18;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      caso1++;
      caso2++;
      p = i, q = j;
      ans = min(ans, solve1(i, j) + solve2(i, j));
    }
  }
  cout << ans << '\n';
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    _solve();
  }
}
