#include <bits/stdc++.h>
using namespace std;
const long double pi = 4 * atan((long double)1);
const long long mod = 1e9 + 7;
const long long inf = 922337203685477;
const long long nax = 0;
long long n, m;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> n >> m;
  vector<vector<long long>> a(n + 5, vector<long long>(m + 5, 0));
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> a[i][j];
    }
  }
  long long ans = 0;
  for (long long j = 0; j < m; j++) {
    vector<long long> freq(n + 5, 0);
    for (long long i = 0; i < n; i++) {
      if (a[i][j] % m != (j + 1) % m) {
        continue;
      } else {
        long long dif = a[i][j] / m;
        if (j == m - 1) {
          dif--;
        }
        if (dif >= n) {
          continue;
        }
        if (dif <= i) {
          freq[i - dif]++;
        } else {
          freq[i + (n - dif)]++;
        }
      }
    }
    long long ret = inf;
    for (long long i = 0; i < n; i++) {
      ret = min(ret, i + (n - freq[i]));
    }
    ans += ret;
  }
  cout << ans << '\n';
}
