#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const int infi = INT_MAX;
const long long infll = LLONG_MAX;
const long double PI = 3.1415926535897932384626;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
long long pow(long long a, long long b, long long m) {
  long long ans = 1;
  while (b) {
    if (b & 1) {
      ans = (ans * a) % m;
    }
    b /= 2;
    a = (a * a) % m;
  }
  return ans;
}
bool isprime(long long n) {
  for (long long i = 2; i * i <= n; ++i)
    if (n % i == 0) {
      return false;
    }
  return true;
}
long long gcd(long long a, long long b) {
  if (b == 0) {
    return a;
  } else {
    return gcd(b, a % b);
  }
}
long long lcm(long long a, long long b) { return ((a / gcd(a, b)) * b); }
long long grid[102][102];
long long dp[102][102];
int n, m;
long long calc(int x, int y, long long val) {
  if (x == n - 1 && y == m - 1) {
    if (grid[x][y] < val) {
      dp[x][y] = 1e18;
      return dp[x][y];
    }
    dp[x][y] = grid[x][y] - val;
    return dp[x][y];
  }
  if (x >= n || y >= m) {
    return 1e18;
  }
  if (grid[x][y] < val) {
    return 1e18;
  }
  if (dp[x][y] != -1) {
    return dp[x][y];
  }
  long long change = grid[x][y] - val;
  long long down = calc(x + 1, y, val + 1);
  long long right = calc(x, y + 1, val + 1);
  dp[x][y] = change + min(down, right);
  return dp[x][y];
}
void solve(int test_case) {
  cin >> n >> m;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      cin >> grid[i][j];
    }
  }
  long long ans = 1e18;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      for (int a = 0; a <= n; ++a) {
        for (int b = 0; b <= m; ++b) {
          dp[a][b] = -1;
        }
      }
      long long base_value = grid[i][j] - (i + j);
      long long local_ans = calc(0, 0, base_value);
      ans = min(ans, local_ans);
    }
  }
  cout << ans << '\n';
}
int main() {
  ios_base ::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int tc = 1;
  cin >> tc;
  while (tc--) {
    solve(tc);
  }
  return 0;
}
