#include <bits/stdc++.h>
using namespace std;
long long mark[200008], shift[200008];
long long countof(long long ori, long long curr, long long n) {
  if (ori == curr) return 0;
  if (ori < curr) return (curr - ori);
  return (curr + n - ori);
}
int main() {
  long long n, m, move, li, ri, val, ache;
  scanf("%lld", &n), scanf("%lld", &m);
  long long ar[n + 2][m + 2];
  for (long long i = 1; i <= n; i++)
    for (long long j = 1; j <= m; j++) scanf("%lld", &ar[i][j]);
  move = 0;
  li = ri = 1;
  for (long long i = 2; i <= n; i++) ri += m;
  for (long long i = 1; i <= m; i++) {
    for (long long j = li, p = 1; j <= ri; j += m, p++) mark[j] = p;
    ache = 0;
    for (long long j = 1; j <= n; j++) {
      if (mark[ar[j][i]]) {
        shift[countof(mark[ar[j][i]], j, n)]++;
        ache++;
      } else
        move++;
    }
    val = 10e16;
    for (long long j = 0; j < n; j++) {
      val = min(val, min((j + (ache - shift[j])), ache));
      shift[j] = 0;
    }
    move += val;
    for (long long j = li; j <= ri; j += m) mark[j] = 0;
    li++;
    ri++;
  }
  printf("%lld", move);
}
