#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  cin >> n >> m;
  int a[n + 1][m + 1];
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> a[i][j];
    }
  }
  int ans = 0;
  for (int i = 1; i <= m; i++) {
    map<int, int> mp;
    map<int, int>::iterator it;
    for (int j = 1; j <= n; j++) {
      if ((a[j][i] - i) % m == 0 &&
          ((a[j][i] - i) / m >= 0 && (a[j][i] - i) / m < n)) {
        int r = (a[j][i] - i) / m + 1;
        if (r <= j) {
          int mov = j - r;
          it = mp.find(mov);
          if (it == mp.end()) {
            mp.insert(make_pair(mov, 1));
          } else {
            it->second++;
          }
        } else {
          int mov = j + n - r;
          it = mp.find(mov);
          if (it == mp.end()) {
            mp.insert(make_pair(mov, 1));
          } else {
            it->second++;
          }
        }
      }
    }
    int minm = n;
    for (it = mp.begin(); it != mp.end(); it++) {
      minm = min(minm, it->first + n - it->second);
    }
    ans += minm;
    mp.clear();
  }
  cout << ans << endl;
}
