#include <bits/stdc++.h>
using namespace std;
const int MX = 2e5 + 5;
vector<vector<int>> mtx;
map<int, int> mp;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int n, m, ans = 0;
  cin >> n >> m;
  mtx.resize(n + 2);
  for (int i = 1, num; i <= n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> num;
      mtx[i].push_back(num);
    }
  }
  for (int j = 0; j < m; j++) {
    for (int i = 1; i <= n; i++) {
      if (mtx[i][j] % m != (j + 1) % m || mtx[i][j] > (n - 1) * m + (j + 1))
        continue;
      int pos = (mtx[i][j] - (j + 1)) / m + 1;
      int sh = i - pos;
      if (sh < 0) sh += n;
      mp[sh]++;
    }
    int mn = 0, mnSh = 0;
    for (auto it : mp) {
      if (it.second - it.first > mn) {
        mn = it.second - it.first;
        mnSh = it.second;
        ans += it.first;
      }
    }
    ans += n - mnSh;
    mp.clear();
  }
  cout << ans << "\n";
  return 0;
}
