#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    x = (x << 1) + (x << 3) + (ch ^ 48);
    ch = getchar();
  }
  return x * f;
}
long long qmi(long long m, long long k, long long p) {
  long long res = 1 % p, t = m;
  while (k) {
    if (k & 1) res = res * t % p;
    t = t * t % p;
    k >>= 1;
  }
  return res;
}
int n, m;
int mapp[200010];
int cnt[200010];
set<int> v;
int main() {
  n = read();
  m = read();
  for (int i = 1; i <= n * m; i++) {
    mapp[i] = read();
  }
  int ans = 0;
  for (int i = 1; i <= m; i++) {
    v.clear();
    for (int j = 1; j <= n; j++) {
      int x = mapp[(j - 1) * m + i];
      int col = x % m;
      if (col == 0) col = m;
      if (col != i) continue;
      if (x > n * m)
        continue;
      else {
        int cntcnt;
        int row;
        if (x % m == 0)
          row = x / m;
        else
          row = x / m + 1;
        if (j >= row) {
          cntcnt = j - row;
        } else {
          cntcnt = j + n - row;
        }
        cnt[cntcnt]++;
        v.insert(cntcnt);
      }
    }
    int sum = n;
    if (v.empty()) {
      ans += sum;
      continue;
    } else {
      set<int>::iterator it1;
      for (it1 = v.begin(); it1 != v.end(); it1++) {
        sum = min(sum, *it1 + n - cnt[*it1]);
        cnt[*it1] = 0;
      }
      ans += sum;
    }
  }
  printf("%d\n", ans);
  return 0;
}
