#include <bits/stdc++.h>
using namespace std;
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long n, m;
  cin >> n >> m;
  vector<long long> v[n];
  for (long long i = 0; i < n; i++) v[i].resize(m, 0);
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < m; j++) cin >> v[i][j];
  long long ans = 0;
  for (long long j = 0; j < m; j++) {
    long long cnt = 0;
    map<long long, long long> mp;
    for (long long i = 0; i < n; i++) {
      if (v[i][j] != i * m + j + 1) cnt++;
      if (((v[i][j] - j - 1) % m == 0) && (v[i][j] - j - 1) >= 0 &&
          (v[i][j] - j - 1) / m < n) {
        mp[(i - (v[i][j] - j - 1) / m + n) % n]++;
      }
    }
    long long tt = cnt;
    for (auto i : mp) {
      tt = min(tt, i.first + n - i.second);
    }
    ans += tt;
  }
  cout << ans << endl;
  return 0;
}
