#include <bits/stdc++.h>
using namespace std;
using namespace std::chrono;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long int n, m;
  cin >> n >> m;
  vector<long long int> ar[n];
  for (long long int x = 0; x < n; x++) {
    ar[x].resize(m);
    for (long long int y = 0; y < m; y++) {
      cin >> ar[x][y];
    }
  }
  long long int ans = 0;
  long long int pro = n * m;
  for (long long int y = 0; y < m; y++) {
    vector<long long int> temp(n, 0);
    long long int rem = (y + 1) % m;
    for (long long int x = 0; x < n; x++) {
      if (ar[x][y] % m == rem) {
        long long int r1 = (ar[x][y] - rem) / m;
        if (rem == 0) {
          r1--;
        }
        if (ar[x][y] <= pro) {
          if (r1 <= x) {
            temp[x - r1]++;
          } else {
            temp[x - r1 + n]++;
          }
        }
      }
    }
    long long int ans1 = (long long int)1e9;
    for (long long int x = 0; x < n; x++) {
      ans1 = min(ans1, x + n - temp[x]);
    }
    ans += ans1;
  }
  cout << ans << "\n";
  return 0;
}
