#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n, m;
  cin >> n >> m;
  vector<vector<long long> > a(m, vector<long long>(n));
  for (long long i = 0; i <= n - 1; i++) {
    for (long long j = 0; j <= m - 1; j++) {
      cin >> a[j][i];
      a[j][i]--;
    }
  }
  long long ans = 0;
  for (long long i = 0; i <= m - 1; i++) {
    vector<long long> temp(n, 0);
    for (long long j = 0; j <= n - 1; j++) {
      if (a[i][j] % m == i) {
        long long x = a[i][j] / m;
        if (x < n) {
          temp[(j - x + n) % n]++;
        }
      }
    }
    long long lol = INT_MAX;
    for (long long j = 0; j <= n - 1; j++) {
      lol = min(lol, (n - temp[j] + j));
    }
    ans += lol;
  }
  cout << ans << "\n";
  return;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t = 1;
  for (long long i = 1; i <= t; i++) {
    solve();
  }
  return 0;
}
