#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  scanf("%d %d", &n, &m);
  vector<vector<int>> vec(n);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      int x;
      scanf("%d", &x);
      vec[i].push_back(x - 1);
    }
  }
  int ans = 0;
  for (int j = 0; j < m; j++) {
    vector<int> tmp(n, 0);
    for (int i = 0; i < n; i++) {
      if (vec[i][j] % m != j || vec[i][j] > n * m) continue;
      int k = vec[i][j] / m;
      tmp[(i - k + n) % n]++;
    }
    int cutu = 1e9;
    for (int i = 0; i < n; i++) cutu = min(cutu, i + n - tmp[i]);
    ans += cutu;
  }
  printf("%d\n", ans);
  return 0;
}
