#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, ans = 0;
  cin >> n >> m;
  vector<vector<int> > mat(n, vector<int>(m));
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> mat[i][j];
      mat[i][j]--;
    }
  }
  for (int j = 0; j < m; j++) {
    vector<int> cnt(n);
    for (int i = 0; i < n; i++) {
      if (mat[i][j] % m != j) continue;
      int pos = mat[i][j] / m;
      if (pos >= n) continue;
      cnt[(i - pos + n) % n]++;
    }
    int mn = INT_MAX;
    for (int i = 0; i < n; i++) {
      mn = min(mn, n - cnt[i] + i);
    }
    ans += mn;
  }
  cout << ans << endl;
}
