#include <bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
const int N = (int)2e5 + 100;
const int M = (int)2e6 + 100;
const int inf = (int)1e9 + 100;
vector<vector<int> > a, was;
int main() {
  mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
  srand(time(0));
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n, m, i, j;
  cin >> n >> m;
  a.resize(n);
  was.resize(n);
  for ((i) = 0; (i) < (n); (i)++) {
    a[i].resize(m);
    was[i].resize(m);
    for ((j) = 0; (j) < (m); (j)++) {
      cin >> a[i][j];
    }
  }
  int ans = 0;
  for ((j) = 0; (j) < (m); (j)++) {
    for ((i) = 0; (i) < (n); (i)++) {
      if ((a[i][j] - j - 1) >= 0 && (a[i][j] - j - 1) % m == 0 &&
          (a[i][j] - j - 1) / m < n) {
        int pos = (a[i][j] - j - 1) / m;
        int c;
        if (pos <= i)
          c = i - pos;
        else
          c = i + n - pos;
        was[c][j]++;
      }
    }
    int o = n;
    for ((i) = 0; (i) < (n); (i)++) {
      o = min(o, n - was[i][j] + i);
    }
    ans += o;
  }
  cout << ans;
}
