#include <bits/stdc++.h>
using namespace std;
void solve();
void fast() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
}
template <typename T>
istream &operator>>(istream &in, vector<T> &ans) {
  for (auto &d : ans) in >> d;
  return in;
}
template <typename T>
ostream &operator<<(ostream &out, vector<T> &ans) {
  for (auto &d : ans) out << d << " ";
  return out;
}
signed main() {
  fast();
  solve();
}
void solve() {
  long long n, m;
  cin >> n >> m;
  long long ans[n][m];
  for (long long i = 0; i < n; ++i)
    for (long long j = 0; j < m; ++j) cin >> ans[i][j];
  long long cnt = 0;
  for (long long j = 0; j < m; ++j) {
    vector<long long> kes(n);
    for (long long i = 0; i < n; ++i) {
      if ((ans[i][j] - j - 1) % m || (ans[i][j] - j - 1) / m >= n)
        kes[i] = n;
      else if (i >= (ans[i][j] - j - 1) / m)
        kes[i] = i - (ans[i][j] - j - 1) / m;
      else
        kes[i] = min(i + n - (ans[i][j] - j - 1) / m, n);
    }
    vector<long long> otrat(n + 1);
    for (long long i = 0; i < n; ++i) otrat[kes[i]]++;
    long long mn = n;
    for (long long i = 0; i <= n; ++i) mn = min(mn, i + n - otrat[i]);
    cnt += mn;
  }
  cout << cnt << endl;
}
