#include <bits/stdc++.h>
using namespace std;
template <typename T, typename U>
inline void amin(T &x, U y) {
  if (y < x) x = y;
}
template <typename T, typename U>
inline void amax(T &x, U y) {
  if (x < y) x = y;
}
long long MOD = 1000000007;
struct Edge {
  int src, dst;
  long long weight;
};
struct BIT {
  int bit[20000];
  int n;
  void add(int k, int x) {
    while (k <= n) {
      bit[k] += x;
      k = k + (k & -k);
    }
  }
  int sum(int k) {
    int ret = 0;
    while (k > 0) {
      ret += bit[k];
      k = k - (k & -k);
    }
    return ret;
  }
  int sum(int a, int b) { return sum(b) - sum(a - 1); }
};
BIT bit[1010];
int num[505 * 505];
int cnt[501 * 501][4];
int ans[505 * 505];
vector<int> tatejun[505], yokojun[505];
int N;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> N;
  for (int(i) = 0; (i) < (int)(N * N); ++(i)) {
    cin >> num[i];
    tatejun[num[i] % N].push_back(num[i]);
    yokojun[(num[i] - 1) / N].push_back(num[i]);
  }
  for (int(i) = 0; (i) < (int)(N); ++(i)) {
    bit[i].n = N + 2;
    for (int(k) = 0; (k) < (int)(N); ++(k)) {
      int x = tatejun[i][k];
      int ban = (x + N - 1) / N;
      bit[i].add(ban, 1);
      int lef = ban - 1 - bit[i].sum(1, ban - 1);
      int rig = N - ban - bit[i].sum(ban + 1, N + 2);
      ans[x] = min(lef, rig);
    }
  }
  for (int(i) = 0; (i) < (int)(N); ++(i)) {
    bit[i + N].n = N + 2;
    for (int(k) = 0; (k) < (int)(N); ++(k)) {
      int x = yokojun[i][k];
      int ban = x % N;
      if (ban == 0) ban += N;
      bit[i + N].add(ban, 1);
      int lef = ban - 1 - bit[i + N].sum(1, ban - 1);
      int rig = N - ban - bit[i + N].sum(ban + 1, N + 2);
      ans[x] = min(ans[x], min(lef, rig));
    }
  }
  int ret = 0;
  for (int(i) = 0; (i) < (int)(N * N); ++(i)) ret += ans[i];
  cout << ret << endl;
}
