#include <bits/stdc++.h>
using namespace std;
long long read() {
  char c = getchar();
  bool flag = 0;
  long long x = 0;
  while (c < '0' || c > '9') {
    if (c == '-') flag = 1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    x = (x << 3) + (x << 1) + c - '0';
    c = getchar();
  }
  return flag ? -x : x;
}
const long long N = 2e5 + 10, INF = 1e13;
vector<long long> a[N];
long long js[N];
int main() {
  long long n = read(), m = read();
  for (long long i = 1; i <= n; i++) {
    a[i].push_back(0);
    for (long long j = 1; j <= m; j++) a[i].push_back(read());
  }
  long long ans = 0;
  for (long long i = 1; i <= m; i++) {
    long long cnt = 0;
    for (long long j = 1; j <= n; j++) {
      if (a[j][i] % m == i % m && a[j][i] <= m * n) {
        long long orig = (a[j][i] - 1) / m + 1;
        if (orig <= j)
          js[j - orig]++;
        else
          js[j + (n - orig)]++;
      } else {
        cnt++;
      }
    }
    long long mi = INF;
    for (long long j = 0; j < n; j++) {
      mi = min(n - cnt - js[j] + j, mi), js[j] = 0;
    }
    ans += mi + cnt;
  }
  printf("%lld\n", ans);
}
