#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  cin >> n >> m;
  vector<int> a[n];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      int x;
      cin >> x;
      x--;
      a[i].push_back(x);
    }
  }
  int ans = 0;
  for (int j = 0; j < m; j++) {
    vector<int> cnt(n);
    int c = 0;
    for (int i = 0; i < n; i++) {
      if (a[i][j] % m != j || a[i][j] / m > n)
        c++;
      else {
        if (i >= a[i][j] / m)
          cnt[i - a[i][j] / m]++;
        else
          cnt[i + n - a[i][j] / m]++;
      }
    }
    int mn = 1e9;
    for (int i = 0; i < n; i++) {
      mn = min(mn, n - cnt[i] + i);
    }
    ans += mn;
  }
  cout << ans << endl;
}
