#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  cin >> n >> m;
  vector<vector<int> > arr(n);
  for (auto &it : arr) it.resize(m);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> arr[i][j];
    }
  }
  int ans = 0;
  for (int i = 0; i < m; i++) {
    vector<int> cnt(n, 0);
    int maxi = -1;
    int idx = -1;
    for (int j = 0; j < n; j++) {
      int belong = (arr[j][i] - (i + 1));
      if ((belong % m) || (arr[j][i]) > (n * m)) continue;
      int pos = belong / m;
      int toGo = (j - pos + n) % n;
      cnt[toGo]++;
      if (maxi < cnt[toGo]) {
        maxi = cnt[toGo];
        idx = toGo;
      }
    }
    int toAdd = n;
    if (maxi != -1) {
      for (int j = 0; j < n; j++) {
        int left = n - cnt[j];
        toAdd = min(toAdd, left + j);
      }
    }
    ans += toAdd;
  }
  cout << ans;
}
