#include <bits/stdc++.h>
using namespace std;
int a[200010], s[200010], n, m, ans, x[200010];
int id(int a, int b) { return (a - 1) * m + b; }
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) scanf("%d", &a[id(i, j)]);
  for (int j = 1; j <= m; j++) {
    for (int i = 0; i < n; i++) x[i] = 0;
    for (int i = 1; i <= n; i++)
      if (a[id(i, j)] % m == j % m && a[id(i, j)] <= n * m) {
        int pp = (int)ceil(1.0 * a[id(i, j)] / m);
        if (pp <= i)
          x[i - pp]++;
        else
          x[i + n - pp]++;
      }
    int anss = 2 * n;
    for (int i = 0; i < n; i++) anss = min(anss, i + n - x[i]);
    ans += anss;
  }
  cout << ans;
  return 0;
}
