#include <bits/stdc++.h>
using namespace std;
struct comp {
  bool operator()(const pair<int, int> &p1, const pair<int, int> &p2) {
    if (p1.first != p2.first) return (p1.first < p2.first);
    return (p1.second > p2.second);
  }
};
int main() {
  std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  int t = 1;
  while (t--) {
    int n, m, x, y;
    cin >> n >> m;
    vector<vector<int> > a(n, vector<int>(m));
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) cin >> a[i][j];
    int ans = 0;
    for (int j = 0; j < m; j++) {
      vector<int> b(n, 0);
      int mi = n;
      for (int i = 0; i < n; i++) {
        y = a[i][j];
        y -= j + 1;
        if (y % m == 0 and y / m < n and y / m >= 0) {
          y /= m;
          y = i - y;
          if (y < 0) y += n;
          b[y]++;
        }
      }
      for (int i = 0; i < n; i++) {
        mi = min(mi, n - b[i] + i);
      }
      ans += mi;
    }
    cout << ans << "\n";
  }
  return 0;
}
