#include <bits/stdc++.h>
const int MAXN = 2e5 + 10;
std::vector<std::vector<int> > matr;
std::vector<int> needed;
int main() {
  std::cin.tie(NULL);
  std::cout.tie(NULL);
  std::ios_base::sync_with_stdio(false);
  int n, m, ans = 0;
  std::cin >> n >> m;
  matr.resize(n, std::vector<int>(m));
  needed.resize(n);
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j) std::cin >> matr[i][j];
  for (int i = 0; i < m; ++i) {
    std::fill(needed.begin(), needed.end(), 0);
    for (int j = 0; j < n; ++j)
      if (matr[j][i] % m == (i + 1) % m && (matr[j][i] - 1) / m < n)
        ++needed[(n + j - (matr[j][i] - 1) / m) % n];
    int min = MAXN;
    for (int j = 0; j < n; ++j) min = std::min(min, j + n - needed[j]);
    ans += min;
  }
  std::cout << ans << '\n';
  return 0;
}
