#include <bits/stdc++.h>
using namespace std;
set<int> shift_votes[200010];
int main() {
  int n, m;
  while (scanf("%d%d", &n, &m) > 0) {
    vector<vector<int> > a(n + 1, vector<int>(m + 1));
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        scanf("%d", &a[i][j]);
      }
    }
    int ans = 0;
    for (int j = 1; j <= m; j++) {
      for (int i = 1; i <= n; i++) {
        if (a[i][j] % m != j % m) continue;
        int r;
        if (j == m) {
          r = a[i][j] / m;
        } else {
          r = a[i][j] / m + 1;
        }
        if (r > n) continue;
        if (r <= i) {
          shift_votes[i - r].insert(a[i][j]);
        } else {
          shift_votes[i + n - r].insert(a[i][j]);
        }
      }
      int best_shift = 0;
      for (int i = 0; i < n; i++) {
        if (i + n - (int)shift_votes[i].size() <
            best_shift + n - (int)shift_votes[best_shift].size()) {
          best_shift = i;
        }
      }
      ans += best_shift + n - (int)shift_votes[best_shift].size();
      for (int i = 0; i < n; i++) {
        shift_votes[i].clear();
      }
    }
    printf("%d\n", ans);
  }
}
