#include <bits/stdc++.h>
using namespace std;
inline int qr() {
  int f = 0, fu = 1;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') fu = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    f = (f << 3) + (f << 1) + c - 48;
    c = getchar();
  }
  return f * fu;
}
const int N = 2e5 + 10;
int n, m, spd[N];
unordered_map<int, int> loc;
vector<int> a[N];
inline void init(int j) {
  for (register int i = 0; i <= n - 1; ++i) spd[i] = i + n;
  loc.clear();
  for (register int i = 1; i <= n; ++i) loc[(i - 1) * m + j] = i;
}
int main() {
  n = qr(), m = qr();
  for (register int i = 1; i <= n; ++i)
    for (register int j = 1; j <= m; ++j) a[i].push_back(qr());
  int ans = 0;
  for (register int i = 0; i <= m - 1; ++i) {
    init(i + 1);
    for (register int j = 1; j <= n; ++j)
      if (loc[a[j][i]]) spd[(j - loc[a[j][i]] + n) % n]--;
    int mn = 0x3f3f3f3f;
    for (register int j = 0; j <= n - 1; ++j) mn = min(mn, spd[j]);
    ans += mn;
  }
  printf("%d\n", ans);
  return 0;
}
