#include <bits/stdc++.h>
using namespace std;
vector<int> s[200001];
int main(int argc, char *argv[]) {
  int n, m, sum;
  cin >> n >> m;
  for (int i = (0); i < (n); i++) {
    for (int j = (0); j < (m); j++) {
      int x;
      cin >> x;
      x--;
      s[i].push_back(x);
    }
  }
  sum = 0;
  for (int j = (0); j < (m); j++) {
    vector<int> cont(n);
    for (int i = (0); i < (n); i++) {
      if ((s[i][j]) % m == j) {
        int pos = (s[i][j] / m);
        if (pos < n) {
          cont[(i - pos + n) % n]++;
        }
      }
    }
    int ok = n - cont[0];
    for (int i = 1; i < n; i++) {
      ok = min(ok, n - cont[i] + i);
    }
    sum = sum + ok;
  }
  cout << sum << endl;
  return 0;
}
