#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 1000;
const long long INF64 = 1e18 + 1000;
const int N = 3 * 1e5 + 1000;
const int MOD = 1e9 + 7;
const double EPS = 1E-9;
long long gcd(long long a, long long b) { return a == 0 ? b : gcd(b % a, a); }
void spr(int x) { cout << setprecision(x) << fixed; }
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n, m;
  cin >> n >> m;
  vector<vector<int>> a(n, vector<int>(m));
  for (int i = 0; i < int(n); ++i) {
    for (int j = 0; j < int(m); ++j) {
      cin >> a[i][j];
      --a[i][j];
    }
  }
  vector<vector<int>> table(m);
  for (int j = 0; j < int(m); ++j) {
    for (int i = 0; i < int(n); ++i) {
      table[j].push_back(j + i * m);
    }
  }
  int ans = 0;
  for (int j = 0; j < int(m); ++j) {
    vector<int> cnt(n);
    for (int i = 0; i < int(n); ++i) {
      auto f = lower_bound(table[j].begin(), table[j].end(), a[i][j]);
      if (f == table[j].end() || *f != a[i][j]) continue;
      int needpos = f - table[j].begin();
      cnt[(i - needpos + n) % n]++;
    }
    int mn = INF;
    for (int i = 0; i < int(n); ++i) {
      mn = min(mn, n - cnt[i] + i);
    }
    ans += mn;
  }
  cout << ans << '\n';
}
