#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 2;
vector<int> ve[N];
int vis[N];
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  int x;
  for (int i = 1; i <= n; i++) {
    ve[i].push_back(0);
    for (int j = 1; j <= m; j++) {
      scanf("%d", &x);
      ve[i].push_back(x);
    }
  }
  int b;
  long long ans = 0;
  for (int i = 1; i <= m; i++) {
    for (int j = 1; j <= n; j++) vis[j] = 0;
    int minn = n;
    for (int j = 1; j <= n; j++) {
      if ((ve[j][i] - i) % m != 0 || ve[j][i] > n * m) continue;
      b = ve[j][i] / m + 1;
      if (ve[j][i] % m == 0) b--;
      if (j - b >= 0)
        b = j - b + 1;
      else
        b = j - b + n + 1;
      vis[b]++;
      if (n - vis[b] + b - 1 < minn) minn = n - vis[b] + b - 1;
    }
    ans += (long long)minn;
  }
  printf("%lld\n", ans);
  return 0;
}
