#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n, m;
  cin >> n >> m;
  long long a[n + 1][m + 1];
  for (long long i = 1; i <= n; i++) {
    for (long long j = 1; j <= m; j++) cin >> a[i][j];
  }
  long long ans = 0;
  for (long long j = 1; j <= m; j++) {
    map<long long, long long> mp;
    for (long long i = 1; i <= n; i++) {
      long long x = a[i][j];
      if (x <= (n - 1) * m + j and (x - j) % m == 0) {
        long long y = (x - j) / m + 1;
        if (y <= i) {
          long long dis = i - y;
          mp[dis]++;
        } else {
          long long dis = i + (n - y);
          mp[dis]++;
        }
      }
    }
    long long res = n;
    for (auto it = mp.begin(); it != mp.end(); ++it) {
      res = min(res, n - it->second + it->first);
    }
    ans += res;
  }
  cout << ans;
  return;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  ;
  long long t;
  t = 1;
  while (t--) solve();
  return 0;
}
