#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-10;
const double Pi = 3.1415926535897932;
const int dir[4][2] = {-1, 0, 0, -1, 1, 0, 0, 1};
const int maxn = 2e5 + 5;
vector<int> G[maxn];
int w[maxn];
int n, m;
int C[maxn * 2];
int solve() {
  for (int i = 0; i <= n * 2; i++) C[i] = 0;
  int ans = n;
  int cnt = 0;
  for (int i = 1; i <= n; i++)
    if (w[i] != -1) {
      if (w[i] <= i)
        C[i - w[i]]++;
      else
        C[n - (w[i] - i)]++;
    } else
      cnt++;
  for (int i = 0; i < n; i++) {
    ans = min(ans, i + n - C[i]);
  }
  return ans;
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      int x;
      scanf("%d", &x);
      G[i].push_back(x);
    }
  }
  int ans = 0;
  for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
      if (G[j][i] <= n * m && G[j][i] % m == (i + 1) % m)
        w[j + 1] = (G[j][i] - i - 1) / m + 1;
      else
        w[j + 1] = -1;
    }
    ans += solve();
  }
  printf("%d\n", ans);
  return 0;
}
