#include <bits/stdc++.h>
int dr[] = {2, 2, -2, -2, 1, -1, 1, -1};
int dc[] = {1, -1, 1, -1, 2, 2, -2, -2};
int dr1[] = {0, 0, 1, 1, 1, -1, -1, -1};
int dc1[] = {1, -1, 1, 0, -1, 0, 1, -1};
int dr2[] = {0, 0, 1, -1};
int dc2[] = {1, -1, 0, 0};
using namespace std;
vector<long long int> adj[400004], adj1[400004];
long long int mark[400004], a[400004];
int main() {
  long long int n, m, i, j, x, k;
  while (cin >> n >> m) {
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        cin >> x;
        adj[i].push_back(x);
      }
    }
    long long int ans = 0;
    for (i = 0; i < m; i++) {
      long long int x = i + 1;
      vector<long long int> v;
      for (j = 0; j < n; j++) {
        long long int p = adj[j][i];
        adj1[p].push_back(j + 1);
        if (adj1[p].size() == 1) v.push_back(p);
      }
      for (j = 0; j < n; j++) {
        long long int p = adj[j][i];
        for (k = 0; k < adj1[x].size(); k++) {
          long long int r = adj1[x][k];
          long long int c = j + 1;
          long long int shift;
          if (r >= c)
            shift = r - c;
          else
            shift = r + (n - c);
          a[shift % n]++;
        }
        x += m;
      }
      long long int min1 = 2000000000000000000;
      for (j = 0; j < n; j++) {
        min1 = min(min1, j + (n - a[j]));
        a[j] = 0;
      }
      ans += min1;
      for (j = 0; j < v.size(); j++) {
        long long int p = v[j];
        adj1[p].clear();
      }
    }
    cout << ans << endl;
  }
  return 0;
}
