#include <bits/stdc++.h>
using namespace std;
const int Inf = (1 << 30) - 1;
const long long lInf = (1LL << 62) - 1;
const int mInf = 0x7f7f7f7f;
const int Maxn = 200010;
vector<int> a[Maxn];
pair<int, int> S[Maxn << 1];
int f[Maxn];
int t[Maxn];
int n, m, ans;
void solve(int k) {
  map<int, int> M;
  for (int i = 1; i <= n; i++) M[++f[i]] = i;
  for (int i = 1; i <= n; i++) t[i] = a[i][k];
  int cnt = 0, tot = 0, minn = Inf;
  for (int i = 1; i <= n; i++) {
    int tmp = M[t[i]];
    if (tmp != 0 && i - tmp != 0)
      S[++tot] = make_pair(i - tmp > 0 ? i - tmp : i - tmp + n, 1);
    if (tmp != 0)
      S[++tot] = make_pair(i - tmp + 1 > 0 ? i - tmp + 1 : i - tmp + n + 1, -1);
    if (t[i] == f[i]) cnt++;
  }
  sort(S + 1, S + tot + 1);
  minn = min(minn, n - cnt);
  int p = 1;
  for (int i = 1; i < n; i++) {
    while (S[p].first <= i && p <= tot) cnt += S[p++].second;
    minn = min(minn, i + n - cnt);
  }
  ans += minn;
}
int main() {
  ios::sync_with_stdio(false);
  cin >> n >> m;
  for (int i = 1; i <= n; i++) {
    a[i].push_back(0);
    for (int x, j = 1; j <= m; j++) cin >> x, a[i].push_back(x);
  }
  for (int i = 1; i <= n; i++) f[i] = (i - 1) * m;
  for (int i = 1; i <= m; i++) solve(i);
  cout << ans << endl;
  return 0;
}
