#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int ans = 0;
  long long int n, m, i, j;
  cin >> n >> m;
  long long int a[n][m];
  for (i = 0; i < n; ++i) {
    for (j = 0; j < m; ++j) {
      cin >> a[i][j];
    }
  }
  for (j = 0; j < m; ++j) {
    set<long long int> s;
    long long int f_a = 1000000000, b[n + 1];
    map<long long int, long long int> c, mp;
    for (i = 0; i < n; ++i) {
      b[i] = i * m + 1 + j;
      c[(i * m + 1 + j)] = i;
      s.insert((i * m + 1 + j));
    }
    for (i = 0; i < n; ++i) {
      if (s.find(a[i][j]) != s.end()) {
        long long int ind = (i - c[a[i][j]]);
        if (ind < 0) {
          ind = ind + n;
        }
        ++mp[ind];
      }
    }
    if (mp.size() == 0) {
      ans += n;
    } else {
      long long int mx = 0;
      for (auto it = mp.begin(); it != mp.end(); ++it) {
        long long int ind = it->first;
        long long int val = it->second;
        long long int dif = val - ind;
        mx = max(mx, dif);
      }
      ans += n - mx;
    }
  }
  cout << ans;
  return 0;
}
