#include <bits/stdc++.h>
using namespace std;
const long long inf = 1e17;
const long long N = 3e6 + 10;
const long long bits = 62;
const long long mod = 1e9 + 7;
const long double pi = 3.14159265358979323846;
long long disp[N];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  std::cout << std::fixed << std::setprecision(20);
  ;
  long long n, m;
  cin >> n >> m;
  vector<vector<long long>> arr(n, vector<long long>(m));
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      cin >> arr[i][j];
    }
  }
  long long ans = 0;
  long long cntr = 0;
  for (long long j = 0; j < m; j++) {
    cntr++;
    long long lans = n;
    for (long long i = 0; i < n; i++) {
      disp[i] = 0;
    }
    for (long long i = 0; i < n; i++) {
      arr[i][j] -= cntr;
      long long index = arr[i][j] / m;
      if (index < n && index >= 0 && index * m == arr[i][j] && arr[i][j] >= 0)
        disp[(i - index + n) % n]++;
    }
    for (long long i = 0; i < n; i++) {
      lans = min(i + n - disp[i], lans);
    }
    ans += lans;
  }
  cout << ans << "\n";
}
