#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<int, int>;
template <typename T>
struct BIT {
  int n;
  vector<T> bit;
  BIT(int n_) : n(n_ + 1), bit(n, 0) {}
  void add(int i, T x) {
    for (int idx = i; idx < n; idx += (idx & -idx)) {
      bit[idx] += x;
    }
  }
  T sum(int i) {
    T s(0);
    for (int idx = i; idx > 0; idx -= (idx & -idx)) {
      s += bit[idx];
    }
    return s;
  }
};
int main() {
  int n;
  cin >> n;
  vector<int> p(n * n);
  for (int i = 0; i < (n * n); ++i) cin >> p[i];
  vector<BIT<int>> col;
  vector<BIT<int>> row;
  BIT<int> b(n);
  for (int i = 0; i < (n); ++i) {
    col.push_back(b);
    for (int j = 0; j < (n); ++j) col[i].add(j + 1, 1);
    row.push_back(b);
    for (int j = 0; j < (n); ++j) row[i].add(j + 1, 1);
  }
  ll ans = 0;
  for (int i = 0; i < (n * n); ++i) {
    int x = (p[i] - 1) % n;
    int y = (p[i] - 1) / n;
    int l, r, u, d;
    if (x == 0)
      l = 0;
    else
      l = row[y].sum(x);
    if (x == n - 1)
      r = 0;
    else
      r = row[y].sum(n) - l - 1;
    if (y == 0)
      u = 0;
    else
      u = col[x].sum(y);
    if (y == n - 1)
      d = 0;
    else
      d = col[x].sum(n) - u - 1;
    ans += min({l, r, u, d});
    row[y].add(x + 1, -1);
    col[x].add(y + 1, -1);
  }
  cout << ans << endl;
}
