#include <bits/stdc++.h>
using namespace std;
const long long INF = 2e18 + 5;
long long a[105][105];
long long dp[105][105];
vector<long long> v;
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    long long res = INF;
    int n, m;
    scanf("%d %d", &n, &m);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        scanf("%lld", &a[i][j]);
        a[i][j] -= i + j;
        v.push_back(a[i][j]);
      }
    }
    sort(v.begin(), v.end());
    for (long long mn : v) {
      for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++) dp[i][j] = INF;
      for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
          if (a[i][j] < mn) a[i][j] = INF;
      dp[0][0] = a[0][0];
      for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
          if (i > 0) dp[i][j] = min(dp[i][j], dp[i - 1][j] + a[i][j]);
          if (j > 0) dp[i][j] = min(dp[i][j], dp[i][j - 1] + a[i][j]);
        }
      }
      if (dp[n - 1][m - 1] < INF)
        res = min(res, dp[n - 1][m - 1] - mn * (n + m - 1));
    }
    printf("%lld\n", res);
  }
}
