#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  int ara[n][m];
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> ara[i][j];
      --ara[i][j];
    }
  int ans = 0;
  for (int i = 0; i < m; i++) {
    int temp[n + 5];
    memset(temp, 0, sizeof temp);
    for (int j = 0; j < n; j++) {
      if (ara[j][i] % m == i) {
        int pos = ara[j][i] / m;
        if (pos < n) temp[(j - pos + n) % n]++;
      }
    }
    int mx = 1e9;
    for (int i = 0; i < n; i++) {
      int now = (i + n - temp[i]);
      mx = min(mx, now);
    }
    ans += mx;
  }
  cout << ans << endl;
}
