#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<int> input;
void init() {
  scanf("%d%d", &n, &m);
  input.resize(n * m);
  for (int i = 0; i < n * m; i++) scanf("%d", &input[i]), input[i]--;
}
void solve() {
  vector<int> v(n);
  int ans = 0;
  for (int c = 0; c < m; c++) {
    int mn = 0;
    vector<int> cnt(n);
    for (int i = 0; i < n; i++) v[i] = input[i * m + c];
    for (int i = 0; i < n; i++) {
      if (v[i] % m != c) continue;
      int pos = v[i] / m;
      if (pos >= n) continue;
      int ans = i - pos;
      if (ans < 0) ans += n;
      cnt[ans]++;
    }
    for (int i = 0; i < n; i++) mn = min(mn, i - cnt[i]);
    ans += n + mn;
  }
  printf("%d\n", ans);
}
int main() {
  init();
  solve();
}
