#include <bits/stdc++.h>
using namespace std;
;
void solve() {
  long long n, m;
  cin >> n >> m;
  long long a[n][m];
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> a[i][j];
      a[i][j] -= j + 1;
      if (a[i][j] % m)
        a[i][j] = (long long)(1e18);
      else
        a[i][j] /= m, a[i][j] = i - a[i][j];
    }
  }
  long long ans = 0;
  for (long long j = 0; j < m; j++) {
    map<long long, long long> used, unused;
    long long mn = (long long)(1e18), curr;
    for (long long i = 0; i < n; i++) {
      used[a[i][j]]++;
    }
    for (long long i = 0; i < n; i++) {
      curr = used[i];
      curr += unused[i - n];
      mn = min(mn, i + n - curr);
      unused[a[i][j]]++, used[a[i][j]]--;
      curr = 0;
    }
    ans += mn;
  }
  cout << ans << '\n';
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  clock_t start, end;
  start = clock();
  cout << fixed << setprecision(15);
  while (t--) {
    solve();
  }
  end = clock();
  double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
}
