#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;
int n, m;
int **a;
int cnt[maxn];
void Init() {
  a = (int **)malloc(sizeof(int *) * (n + 5));
  for (int i = 1; i <= n + 3; i++) {
    a[i] = (int *)malloc(sizeof(int) * (m + 5));
  }
}
void print() {
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      printf("%d ", a[i][j]);
    }
    putchar('\n');
  }
}
int main() {
  while (scanf("%d%d", &n, &m) != EOF) {
    int ans = 0;
    Init();
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        scanf("%d", &a[i][j]);
      }
    }
    for (int j = 1; j <= m; j++) {
      int ma = n;
      for (int k = 0; k < n; k++) cnt[k] = 0;
      for (int i = 1; i <= n; i++) {
        int ma_val = (n - 1) * m + j;
        if (a[i][j] % m == j % m && a[i][j] >= j && a[i][j] <= ma_val) {
          int row = (a[i][j] - j) / m + 1;
          cnt[(i - row + n) % n]++;
        }
      }
      for (int k = 0; k < n; k++) {
        ma = min(ma, n - cnt[k] + k);
      }
      ans += ma;
    }
    printf("%d\n", ans);
  }
  return 0;
}
