#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
const long long MOD = 1e9 + 7;
const long long INF = 1e18;
inline long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
inline int lb(int x) { return x & -x; }
long long qpow(long long base, int n) {
  if (base == 0) return 0;
  long long ans = 1;
  while (n) {
    if (n & 1) ans *= base;
    n >>= 1;
    base *= base;
  }
  return ans;
}
int n, m, ans;
map<pair<int, int>, int> mp;
pair<int, int> pos(int val) {
  int x, y;
  if (val % m == 0) {
    x = val / m;
    y = m;
  } else {
    x = val / m + 1;
    y = val % m;
  }
  return make_pair(x, y);
}
int main() {
  scanf("%d%d", &n, &m);
  vector<int> step(n + 2);
  for (int i = (1); i <= (n); ++i)
    for (int j = (1); j <= (m); ++j) {
      int tmp;
      scanf("%d", &tmp);
      mp[make_pair(i, j)] = tmp;
    }
  for (int j = (1); j <= (m); ++j) {
    for (int i = (0); i <= (n); ++i) step[i] = 0;
    for (int i = (1); i <= (n); ++i) {
      pair<int, int> to = pos(mp[make_pair(i, j)]);
      if (to.second != j || to.first > n) continue;
      if (to.first <= i)
        ++step[i - to.first];
      else
        ++step[i + n - to.first];
    }
    int tmp = 0;
    for (int i = 1; i < n; ++i)
      if (n - step[tmp] + tmp > n - step[i] + i) tmp = i;
    ans += n - step[tmp] + tmp;
  }
  cout << ans << '\n';
}
