#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int n, m, res = 0;
  cin >> n >> m;
  vector<vector<long long int> > v(n, vector<long long int>(m));
  for (long long int i = 0; i < n; i++) {
    for (long long int j = 0; j < m; j++) {
      cin >> v[i][j];
      v[i][j]--;
    }
  }
  for (long long int j = 0; j < m; j++) {
    vector<long long int> cnt(n);
    for (long long int i = 0; i < n; i++) {
      if (v[i][j] % m == j) {
        long long int k = v[i][j] / m;
        if (k < n) cnt[(i - k + n) % n]++;
      }
    }
    long long int cur = n - cnt[0];
    for (long long int i = 0; i < n; i++) cur = min(cur, n - cnt[i] + i);
    res += cur;
  }
  cout << res << endl;
  return 0;
}
