#include <bits/stdc++.h>
using namespace std;
const int N = 500001;
int b[N], *a[N];
int c[N];
int main(void) {
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 0; i != n; ++i) a[i] = b + (i * m);
  for (int i = 0; i != n; ++i)
    for (int j = 0; j != m; ++j) scanf("%d", &a[i][j]), a[i][j]--;
  int ans = 0;
  for (int j = 0; j != m; ++j) {
    fill_n(c, n, n);
    for (int i = 0; i != n; ++i) {
      if (a[i][j] % m != j || (a[i][j] - j) / m >= n) continue;
      c[(i - (a[i][j] - j) / m + n) % n]--;
    }
    int res = INT_MAX;
    for (int i = 0; i != n; ++i) res = min(res, c[i] + i);
    ans += res;
  }
  printf("%d\n", ans);
  return 0;
}
