#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using vl = vector<ll>;
template <class T>
using vc = vector<T>;
template <class T>
using vvc = vector<vector<T>>;
template <class T>
inline bool chmax(T& a, const T& b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
inline bool chmin(T& a, const T& b) {
  if (b < a) {
    a = b;
    return 1;
  }
  return 0;
}
void init() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(15);
}
const ll INF = 5e18;
const ld EPS = 1e-11;
const ld PI = acos(-1.0L);
const ll MOD = 1e9 + 7;
template <typename T>
struct BIT {
  ll n;
  vector<T> d;
  BIT(ll n = 0) : n(n), d(n + 1) {}
  void add(ll i, T x = 1) {
    for (i++; i <= n; i += i & -i) {
      d[i] += x;
    }
  }
  T sum(ll i) {
    T x = 0;
    for (i++; i; i -= i & -i) {
      x += d[i];
    }
    return x;
  }
};
ll A[250000];
int main() {
  init();
  ll N;
  cin >> N;
  for (ll i = 0; i < (N * N); i++) cin >> A[i], A[i]--;
  vc<BIT<ll>> btr(N, BIT<ll>(N)), btc(N, BIT<ll>(N));
  for (ll i = 0; i < (N); i++)
    for (ll j = 0; j < (N); j++) btr[i].add(j, 1), btc[i].add(j, 1);
  ll ans = 0;
  for (ll i = 0; i < (N * N); i++) {
    ll r = A[i] / N, c = A[i] % N;
    ll t = INF;
    chmin(t, btr[c].sum(r - 1));
    chmin(t, btr[c].sum(N - 1) - btr[c].sum(r));
    chmin(t, btc[r].sum(c - 1));
    chmin(t, btc[r].sum(N - 1) - btc[r].sum(c));
    btr[c].add(r, -1), btc[r].add(c, -1);
    ans += t;
  }
  cout << ans << endl;
}
