#include <bits/stdc++.h>
using namespace std;
using int64 = long long;
const int MAX = 100;
const int64 INF = numeric_limits<int64>::max();
int64 grid[MAX][MAX];
int64 dp[MAX][MAX];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int tc;
  cin >> tc;
  for (int _ = 0; _ < tc; _++) {
    int n, m;
    cin >> n >> m;
    for (int x = 0; x < n; x++)
      for (int y = 0; y < m; y++) {
        cin >> grid[x][y];
      }
    int64 ans = INF;
    for (int bx = 0; bx < n; bx++)
      for (int by = 0; by < m; by++) {
        int64 base = grid[bx][by] - bx - by;
        for (int x = 0; x < n; x++)
          for (int y = 0; y < m; y++) {
            dp[x][y] = INF;
            int64 delta = grid[x][y] - (base + x + y);
            if (delta < 0) {
              continue;
            }
            if (x == 0 and y == 0) {
              dp[x][y] = delta;
            }
            if (x > 0 and dp[x - 1][y] != INF) {
              dp[x][y] = min(dp[x][y], dp[x - 1][y] + delta);
            }
            if (y > 0 and dp[x][y - 1] != INF) {
              dp[x][y] = min(dp[x][y], dp[x][y - 1] + delta);
            }
          }
        ans = min(ans, dp[n - 1][m - 1]);
      }
    cout << ans << '\n';
  }
}
