#include <bits/stdc++.h>
using namespace std;
mt19937 rng32(chrono::steady_clock::now().time_since_epoch().count());
long long inf = 1e18, MOD = 1e9 + 7;
long long n, m, k, ar[1000005], br[1000005];
string s, s1;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int ti = 1;
  while (ti--) {
    cin >> n >> m;
    vector<vector<long long> > in(n + 1, vector<long long>(m + 1, 0));
    for (long long i = 1; i < n + 1; i++)
      for (long long j = 1; j < m + 1; j++) cin >> in[i][j];
    long long ans = 0;
    for (long long j = 1; j < m + 1; j++) {
      vector<long long> shift(n, 0);
      for (long long i = 1; i < n + 1; i++) {
        if ((in[i][j] - j) % m == 0 && in[i][j] >= j && in[i][j] <= (n * m)) {
          long long cor = (in[i][j] - j) / m + 1;
          shift[(i - cor + n) % n]++;
        }
      }
      long long temp = n;
      for (long long i = 0; i < n; i++) {
        temp = min(temp, i + n - shift[i]);
      }
      ans += temp;
    }
    cout << ans << endl;
  }
  return 0;
}
