#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pil = pair<int, ll>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
const int INF = 1e9;
const ll LLINF = 1e18;
const ll MOD = 1e9 + 7;
const double EPS = 1e-10;
const double PI = acos(-1);
template <class T>
inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}
struct BinaryIndexedTree {
  int n;
  vector<int> bit;
  BinaryIndexedTree(int _n) {
    n = _n;
    bit.resize(_n + 1);
  }
  void add(int i, int x) {
    while (i <= n) {
      bit[i] += x;
      i += i & -i;
    }
  }
  int sum(int i) {
    int s = 0;
    while (i > 0) {
      s += bit[i];
      i -= i & -i;
    }
    return s;
  }
  int getSum(int i, int j) { return sum(j) - sum(i - 1); }
};
int main() {
  int n;
  cin >> n;
  int m = n * n;
  vector<int> p(m);
  for (int i = 0; i < m; i++) cin >> p[i];
  vector<BinaryIndexedTree> ybit, xbit;
  for (int i = 0; i < n + 2; i++) {
    ybit.push_back(BinaryIndexedTree(n + 2));
    xbit.push_back(BinaryIndexedTree(n + 2));
  }
  for (int j = 1; j <= n; j++) {
    for (int i = 1; i <= n; i++) ybit[j].add(i, 1);
    for (int i = 1; i <= n; i++) xbit[j].add(i, 1);
  }
  int ans = 0;
  for (int i = 0; i < m; i++) {
    int y = (p[i] + n - 1) / n;
    int x = p[i] % n;
    if (x == 0) x += n;
    int left = ybit[y].getSum(0, x - 1);
    int right = ybit[y].getSum(x + 1, n + 1);
    int up = xbit[x].getSum(0, y - 1);
    int down = xbit[x].getSum(y + 1, n + 1);
    ans += min(left, min(right, min(up, down)));
    ybit[y].add(x, -1);
    xbit[x].add(y, -1);
  }
  cout << ans << endl;
}
