#include <bits/stdc++.h>
using namespace std;
signed main() {
  long long n, m;
  cin >> n >> m;
  long long ans = 0;
  vector<vector<long long> > a(n, vector<long long>(m, 0));
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> a[i][j];
      a[i][j]--;
    }
  }
  for (long long j = 0; j < m; j++) {
    vector<long long> need(n, 0);
    long long dp = n;
    for (long long i = 0; i < n; i++) {
      long long x = a[i][j];
      if (x % m != j || x > (n - 1) * m + j) continue;
      need[(i - x / m + n) % n]++;
      dp = min(dp, ((i - x / m + n) % n) + n - need[(i - x / m + n) % n]);
    }
    ans += dp;
  }
  cout << ans;
}
