#include <bits/stdc++.h>
using namespace std;
struct _ {
  ios_base::Init i;
  _() { ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL); }
} _;
template <class c>
struct rge {
  c b, e;
};
template <class c>
rge<c> range(c i, c j) {
  return rge<c>{i, j};
}
template <class c>
auto dud(c* x) -> decltype(cerr << *x, 0);
template <class c>
char dud(...);
struct debug {
  template <class c>
  debug& operator<<(const c&) {
    return *this;
  }
};
const int MOD = 1e9 + 7;
class MainClass {
 public:
  void solve() {
    long long n, m;
    cin >> n >> m;
    vector<vector<long long>> grid(n, vector<long long>(m, 0));
    for (auto& i : grid)
      for (auto& j : i) cin >> j;
    long long ans = 0;
    for (int j = 0; j <= m - 1; j++) {
      vector<long long> pre(n, n);
      for (int i = 0; i <= n - 1; i++) pre[i] += i;
      for (int k = 0; k <= n - 1; k++) {
        if ((grid[k][j] - j - 1) % m != 0) continue;
        int kk = (grid[k][j] - j - 1) / m;
        if ((kk < 0) or (kk >= n)) continue;
        long long i = k - (grid[k][j] - j - 1) / m;
        if ((0 <= i) and (i < n)) {
          pre[i]--;
        }
        i = n + k - (grid[k][j] - j - 1) / m;
        if ((0 <= i) and (i < n)) {
          pre[i]--;
        }
      }
      ans += *min_element(pre.begin(), pre.end());
    }
    cout << ans;
    return;
  }
};
int main() {
  int test = 1;
  for (int tst = 1; tst <= test; ++tst) {
    MainClass Ausmosian;
    Ausmosian.solve();
    cout << "\n";
  }
  return 0;
}
