#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
const int INFi = 1e9 * 2;
const int maxN = 1000001;
long long md = 1000000007;
void solve() {
  long long n, m;
  cin >> n >> m;
  vector<vector<long long>> t(n, vector<long long>(m, 0));
  for (int i = 0; (i) < n; ++(i)) {
    for (int j = 0; (j) < m; ++(j)) cin >> t[i][j];
  }
  long long answer = 0;
  for (int j = 0; (j) < m; ++(j)) {
    vector<long long> c(n, 0);
    for (int i = 0; (i) < n; ++(i)) {
      if (t[i][j] % m == (j + 1) % m && (j + 1) <= t[i][j] &&
          t[i][j] <= m * (n - 1) + (j + 1)) {
        int f = t[i][j] - (j + 1);
        f /= m;
        int ans = i - f;
        if (ans < 0) ans += n;
        if (ans >= n) ans %= n;
        c[ans]++;
      }
    }
    long long ans_cur = n;
    for (int i = 0; (i) < n; ++(i)) {
      long long ans2 = i;
      ans2 += n - c[i];
      ans_cur = min(ans_cur, ans2);
    }
    answer += ans_cur;
  }
  cout << answer;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  int tests = 1;
  for (int _ = 0; (_) < tests; ++(_)) {
    solve();
  }
  return 0;
}
