#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pll = pair<ll, ll>;
const ll MAXN = 200 * 1000 + 19;
const ll MOD = 1e9 + 7;
const ll inf = 4e18 + 19;
ll n, m, ans = 0;
vector<ll> vec[MAXN];
int main() {
  ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
  cin >> n >> m;
  for (int i = 0; i < n; i++)
    for (int j = 0, tmp; j < m; j++) {
      cin >> tmp;
      vec[i].push_back(tmp - 1);
    }
  for (int j = 0; j < m; j++) {
    vector<ll> cnt(n);
    for (int i = 0; i < n; i++)
      if (vec[i][j] % m == j) {
        ll pos = vec[i][j] / m;
        if (pos < n) cnt[abs(i - pos + n) % n]++;
      }
    ll mn = inf;
    for (int i = 0; i < n; i++) mn = min(mn, n - cnt[i] + i);
    ans += mn;
  }
  cout << ans;
  return (0);
}
