#include <bits/stdc++.h>
using namespace std;
using ULL = unsigned long long;
using UL = unsigned;
using LL = long long;
struct Problem {
  void Solve() {
    UL H, W;
    cin >> H >> W;
    vector<vector<UL>> matrix(W);
    for (UL y = 0; y < (H); y++) {
      for (UL x = 0; x < (W); x++) {
        UL v;
        cin >> v;
        v--;
        if (v % W == x && v < H * W)
          matrix[x].push_back(v / W);
        else
          matrix[x].push_back(1000000);
      }
    }
    UL ans = 0;
    for (UL x = 0; x < (W); x++) {
      UL ansbuf = H;
      vector<UL> buf(H);
      for (UL y = 0; y < (H); y++) buf[y] = y + H;
      for (UL y = 0; y < (H); y++) {
        if (matrix[x][y] == 1000000)
          continue;
        else
          buf[(y + H - matrix[x][y]) % H]--;
      }
      for (UL y = 0; y < (H); y++) {
        ansbuf = min(ansbuf, buf[y]);
      }
      ans += ansbuf;
    }
    cout << ans << endl;
  }
  Problem();
};
int main() {
  unique_ptr<Problem> p(new Problem());
  p->Solve();
  return 0;
}
Problem::Problem() { cout << fixed << setprecision(10); }
