#include <bits/stdc++.h>
using namespace std;
int n, m, ans, cur[2001000];
vector<vector<int> > a;
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m;
  a.resize(n);
  for (int i = 0; i < n; i++) a[i].resize(m);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) cin >> a[i][j], a[i][j]--;
  for (int j = 0; j < m; j++) {
    int Cur = 2e5;
    for (int i = 0; i < n; i++) cur[i] = i + n;
    for (int i = 0; i < n; i++) {
      int x = a[i][j];
      if ((x % m) != j) continue;
      x -= j;
      if (x / m >= n) continue;
      x /= m;
      cur[((i - x) % n + n) % n]--;
    }
    for (int i = 0; i < n; i++) Cur = min(Cur, cur[i]);
    ans += Cur;
  }
  cout << ans << endl;
  return 0;
}
