#include <bits/stdc++.h>
using namespace std;
unsigned long long int minimum(unsigned long long int a,
                               unsigned long long int b) {
  return ((a <= b) ? a : b);
}
unsigned long long int findAns(vector<vector<long long int>> &heights) {
  int i, j;
  int n = heights.size(), m = heights[0].size();
  unsigned long long int answers[n][m];
  for (i = 0; i < n; i += 1) {
    for (j = 0; j < m; j += 1) {
      if (i == 0 && j == 0) {
        answers[i][j] = 0;
      } else if (i == 0) {
        if (heights[0][0] + i + j > heights[i][j]) {
          answers[i][j] = 10000000000000000001;
        } else {
          answers[i][j] =
              (heights[i][j] - heights[0][0] - i - j) + answers[i][j - 1];
          answers[i][j] = minimum(answers[i][j], 10000000000000000001);
        }
      } else if (j == 0) {
        if (heights[0][0] + i + j > heights[i][j]) {
          answers[i][j] = 10000000000000000001;
        } else {
          answers[i][j] =
              (heights[i][j] - heights[0][0] - i - j) + answers[i - 1][j];
          answers[i][j] = minimum(answers[i][j], 10000000000000000001);
        }
      } else {
        if (heights[0][0] + i + j > heights[i][j]) {
          answers[i][j] = 10000000000000000001;
        } else {
          answers[i][j] = (heights[i][j] - heights[0][0] - i - j) +
                          minimum(answers[i][j - 1], answers[i - 1][j]);
          answers[i][j] = minimum(answers[i][j], 10000000000000000001);
        }
      }
    }
  }
  return answers[n - 1][m - 1];
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  int i, j;
  int test, n, m;
  unsigned long long int temp;
  cin >> test;
  while (test--) {
    cin >> n >> m;
    vector<vector<long long int>> heights(n);
    for (i = 0; i < n; i += 1) {
      for (j = 0; j < m; j += 1) {
        cin >> temp;
        heights[i].push_back(temp);
      }
    }
    unsigned long long int ans = findAns(heights);
    long long int initial_height = heights[0][0];
    for (i = 0; i < n; i += 1) {
      for (j = 0; j < m; j += 1) {
        if (initial_height > heights[i][j] - i - j) {
          heights[0][0] = heights[i][j] - i - j;
          ans =
              minimum(ans, (initial_height - heights[0][0]) + findAns(heights));
        }
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
