#include <bits/stdc++.h>
using namespace std;
int main() {
  long long m, n;
  cin >> m >> n;
  int arr[m][n];
  for (int i = 0; i < m; i++)
    for (int j = 0; j < n; j++) {
      cin >> arr[i][j];
      arr[i][j] = arr[i][j] - (1);
    }
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    vector<long long> cnt(m, 0);
    for (int j = 0; j < m; j++) {
      if (arr[j][i] % n == i) {
        int a = arr[j][i] / n;
        if (a < m) a = (j - a + m) % m;
        if (a < m && a >= 0) cnt[a]++;
      }
    }
    long long d = m - cnt[0];
    for (int k = 1; k < m; k++) d = min(d, m - cnt[k] + k);
    ans = ans + d;
  }
  cout << ans << endl;
}
