#include <bits/stdc++.h>
using namespace std;
int num[200005];
int **Arraye;
int ans = 0;
int main() {
  int n, m;
  cin >> n >> m;
  Arraye = new int *[n + 2];
  for (int i = 0; i <= n; i++) Arraye[i] = new int[m + 2];
  int temp;
  for (int i = 0; i <= n; i++) {
    num[i] = 0;
  }
  int sum = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> temp;
      if ((temp % m == j || temp % m == 0 && j == m) &&
          temp <= (n - 1) * m + j) {
        if (temp % m == 0 && j == m) {
          int mov = (temp - j) / m;
          Arraye[i][j] = (i - mov + n) % n;
        } else {
          int mov = (temp - j) / m;
          Arraye[i][j] = (i - mov + n) % n;
        }
      } else {
        Arraye[i][j] = n;
      }
    }
  }
  for (int j = 1; j <= m; j++) {
    int max = -1;
    int maxi;
    for (int i = 0; i < n; i++) {
      if (++num[Arraye[i][j]] > max) {
        max = num[Arraye[i][j]];
        maxi = i;
      }
    }
    int now = n;
    for (int i = 0; i < n; i++) {
      now = min(now, Arraye[i][j] + n - num[Arraye[i][j]]);
    }
    sum += Arraye[maxi][j];
    sum += (n - num[Arraye[maxi][j]]);
    for (int i = 0; i <= n; i++) {
      num[i] = 0;
    }
    ans += now;
  }
  cout << ans << '\n';
  return 0;
}
