#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 100;
int main() {
  int m, n;
  int ans = 0;
  cin >> m >> n;
  int Data[m + 5][n + 5];
  int cnt[m + 5];
  for (int i = 0; i < m; i++)
    for (int j = 0; j < n; j++) scanf("%d", &Data[i][j]);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) cnt[j] = 0;
    for (int j = 0; j < m; j++) {
      if ((Data[j][i] - 1) % n == i && Data[j][i] <= n * m) {
        int pos = (Data[j][i] - 1) / n;
        int distance = j - pos;
        if (distance < 0) {
          distance += m;
        }
        cnt[distance]++;
      }
    }
    int INF = 0x3f3f3f3f;
    for (int j = 0; j < m; j++) INF = min(INF, m + j - cnt[j]);
    ans += INF;
  }
  cout << ans << endl;
  return 0;
}
