#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
int main() {
  int n, m;
  cin >> n >> m;
  vector<vector<int>> a(n, vector<int>(m));
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++) {
      cin >> a[i][j];
      a[i][j]--;
    }
  int ans = 0;
  for (int j = 0; j < m; j++) {
    vector<int> cost(n);
    for (int i = 0; i < n; i++) cost[i] = i + n;
    for (int i = 0; i < n; i++) {
      if (a[i][j] % m == j && a[i][j] < n * m) {
        int h = i - a[i][j] / m;
        if (h < 0) h += n;
        cost[h]--;
      }
    }
    ans += *min_element(cost.begin(), cost.end());
  }
  cout << ans << '\n';
  return 0;
}
