#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n, m;
  cin >> n >> m;
  vector<vector<long long> > cost(m, vector<long long>(n, n));
  for (int i = (0); i < (m); ++i)
    for (int j = (0); j < (n); ++j) cost[i][j] += j;
  vector<vector<long long> > mat(n, vector<long long>(m));
  for (int i = (0); i < (n); ++i)
    for (int j = (0); j < (m); ++j) {
      cin >> mat[i][j];
    }
  for (int j = (0); j < (m); ++j) {
    for (int i = (0); i < (n); ++i) {
      int val = mat[i][j];
      val -= j + 1;
      if (val % m == 0) {
        int k = val / m;
        if (k < n) {
          int shft = 0;
          if (k <= i)
            shft = i - k;
          else
            shft = i + n - k;
          cost[j][shft]--;
        }
      }
    }
  }
  vector<long long> ans(m, n);
  for (int j = (0); j < (m); ++j) {
    int tot = n;
    for (int i = (0); i < (n); ++i)
      tot = ((tot) < (cost[j][i]) ? (tot) : (cost[j][i]));
    ans[j] = ((ans[j]) < (tot) ? (ans[j]) : (tot));
  }
  cout << accumulate(ans.begin(), ans.end(), 0LL) << endl;
}
