#include <bits/stdc++.h>
using namespace std;
inline void read(int &x) {
  char ch = getchar();
  x = 0;
  while (!isdigit(ch)) ch = getchar();
  while (isdigit(ch)) x = x * 10 + ch - 48, ch = getchar();
}
const int N = 2e5 + 10;
int n, m, res, c[N];
vector<int> v[N];
signed main() {
  read(n), read(m);
  int x;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) read(x), v[i].push_back(x);
  for (int j = 1; j <= m; ++j) {
    for (int i = 0; i < n; ++i) c[i] = 0;
    int ans = 1e9, tmp = 0;
    for (int i = 1; i <= n; ++i) {
      int t = v[i][j - 1];
      if ((t - j) % m == 0 && t <= n * m) ++c[(i - (t - j) / m - 1 + n) % n];
    }
    for (int i = 0; i < n; ++i) ans = min(ans, i + n - c[i]);
    res += ans;
  }
  cout << res << endl;
  return 0;
}
