#include <bits/stdc++.h>
using namespace std;
const long INF = 1000 * 1000 * 1000 + 7;
int main() {
  std::ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n, m, x = 1, d, ans = 0, y;
  cin >> n >> m;
  int a[n + 1][m + 1];
  map<int, int> mp[m + 1], mx;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> a[i][j];
      mp[j][x] = i;
      x++;
    }
  }
  for (int i = 1; i <= m; i++) {
    for (int j = 1; j <= n; j++) {
      if (mp[i][a[j][i]] == 0) {
        continue;
      }
      d = j - mp[i][a[j][i]];
      d += n;
      d %= n;
      mx[d]++;
    }
    y = n;
    for (auto it : mx) {
      y = min(it.first + n - it.second, y);
    }
    ans += y;
    mx.clear();
  }
  cout << ans << '\n';
}
