#include <bits/stdc++.h>
using namespace std;
int n, m;
int** a;
int main() {
  ios_base::sync_with_stdio(false);
  cout.tie(0);
  cin.tie(0);
  cin >> n >> m;
  a = new int*[n];
  for (int i = 0; i < n; ++i) {
    a[i] = new int[m];
    for (int j = 0; j < m; ++j) cin >> a[i][j];
  }
  int ans = 0;
  for (int j = 0; j < m; ++j) {
    int* b = new int[n];
    for (int i = 0; i < n; ++i) b[i] = i + n;
    for (int i = 0; i < n; ++i) {
      if ((a[i][j] - j - 1) % m || a[i][j] > n * m) continue;
      --b[(i - (a[i][j] - j - 1) / m + n) % n];
    }
    ans += *min_element(b, b + n);
  }
  cout << ans << '\n';
}
