#include <bits/stdc++.h>
using namespace std;
template <typename Arg1>
void __f(const char* name, Arg1&& arg1) {
  std::cerr << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args) {
  const char* comma = strchr(names + 1, ',');
  std::cerr.write(names, comma - names) << " : " << arg1 << " | ";
  __f(comma + 1, args...);
}
const long long hell = round(1e18);
signed solve() {
  long long n;
  cin >> n;
  long long m;
  cin >> m;
  vector<vector<long long>> a(n, vector<long long>(m));
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> a[i][j];
      a[i][j]--;
    }
  }
  long long sm = 0;
  for (long long mi = 0; mi < m; mi++) {
    vector<long long> r(n, 0);
    for (long long i = 0; i < n; i++) {
      long long k = a[i][mi] - mi;
      if (k % m == 0) {
        long long idx = k / m;
        long long ti = i - idx;
        if (ti < 0 && idx < n) ti += n;
        if (ti >= 0 && ti < n) r[ti]++;
      }
    }
    long long cmin = hell;
    for (long long i = 0; i < n; i++) {
      long long c = (n - r[i]) + i;
      cmin = min(c, cmin);
    }
    sm += cmin;
  }
  cout << sm;
  return 0;
}
signed main() {
  long long t = 1;
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  while (t--) {
    solve();
  }
  return 0;
}
