#include <bits/stdc++.h>
using namespace std;
vector<long long int> g[1000005];
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int n, m;
  cin >> n >> m;
  long long int a[n + 5][m + 5];
  for (long long int i = 1; i <= n; ++i) {
    for (long long int j = 1; j <= m; ++j) {
      cin >> a[i][j];
    }
  }
  std::pair<long long int, long long int> dp[m + 6];
  long long int ans = 0;
  for (long long int j = 1; j <= m; ++j) {
    std::map<long long int, long long int> z;
    for (long long int i = 1; i <= n; ++i) {
      long long int x = a[i][j];
      if ((x - j) % m != 0) continue;
      long long int p = (x - j) / m + 1;
      if (!(p >= 1 and p <= n)) continue;
      if (p <= i)
        z[(i - p)]++;
      else
        z[(n - p + i)]++;
    }
    long long int mn = n;
    long long int c = 0;
    for (auto &i : z) {
      mn = min(mn, n - i.second + i.first);
    }
    ans += mn;
    z.clear();
  }
  cout << ans << endl;
}
