#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int f = 1, x = 0;
  char ch;
  do {
    ch = getchar();
    if (ch == '-') f = -1;
  } while (ch < '0' || ch > '9');
  do {
    x = x * 10 + ch - '0';
    ch = getchar();
  } while (ch >= '0' && ch <= '9');
  return f * x;
}
const int MAXX = 2e5;
const int N = 2e5;
int n, m;
int f[MAXX + 1];
int ans;
int y[N + 1];
inline int js(int k) {
  int minn = n;
  for (int i = 0; i < n; i++) y[i] = 0;
  for (int i = 1; i <= n; i++) {
    int a = (i - 1) * m + k;
    if (((f[a] - 1) % m + 1) != k) continue;
    int b = (f[a] - 1) / m + 1;
    if (b > n) continue;
    y[(i - b + n) % n]++;
  }
  for (int i = 0; i < n; i++)
    if (i + n - y[i] < minn) minn = i + n - y[i];
  return minn;
}
int main() {
  n = read();
  m = read();
  for (int i = 1; i <= n * m; i++) f[i] = read();
  for (int i = 1; i <= m; i++) ans += js(i);
  printf("%d\n", ans);
  return 0;
}
