#include <bits/stdc++.h>
using namespace std;
using dou = long double;
string yes = "yes";
string Yes = "Yes";
string YES = "YES";
string no = "no";
string No = "No";
string NO = "NO";
template <class T>
inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <class T>
inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
const int INF = 1000000000;
const long long INF64 = 922337203685477580ll;
const long long MOD = 1000000007ll;
const dou pi = 3.141592653589793;
struct LazySegmentTree {
 private:
  int n;
  vector<long long> node, lazy;

 public:
  LazySegmentTree(vector<long long> v) {
    int sz = (int)v.size();
    n = 1;
    while (n < sz) n *= 2;
    node.resize(2 * n - 1);
    lazy.resize(2 * n - 1, 0);
    for (int i = 0; i < sz; i++) node[i + n - 1] = v[i];
    for (int i = n - 2; i >= 0; i--)
      node[i] = node[i * 2 + 1] + node[i * 2 + 2];
  }
  void eval(int k, int l, int r) {
    if (lazy[k] != 0) {
      node[k] += lazy[k];
      if (r - l > 1) {
        lazy[2 * k + 1] += lazy[k] / 2;
        lazy[2 * k + 2] += lazy[k] / 2;
      }
      lazy[k] = 0;
    }
  }
  void add(int a, int b, long long x, int k = 0, int l = 0, int r = -1) {
    if (r < 0) r = n;
    eval(k, l, r);
    if (b <= l || r <= a) return;
    if (a <= l && r <= b) {
      lazy[k] += (r - l) * x;
      eval(k, l, r);
    } else {
      add(a, b, x, 2 * k + 1, l, (l + r) / 2);
      add(a, b, x, 2 * k + 2, (l + r) / 2, r);
      node[k] = node[2 * k + 1] + node[2 * k + 2];
    }
  }
  long long getsum(int a, int b, int k = 0, int l = 0, int r = -1) {
    if (r < 0) r = n;
    eval(k, l, r);
    if (b <= l || r <= a) return 0;
    if (a <= l && r <= b) return node[k];
    long long vl = getsum(a, b, 2 * k + 1, l, (l + r) / 2);
    long long vr = getsum(a, b, 2 * k + 2, (l + r) / 2, r);
    return vl + vr;
  }
};
int main() {
  int n;
  std::cin >> n;
  std::vector<int> p(n * n);
  for (int i = 0; i < (int)(n * n); i++) std::cin >> p[i];
  ;
  std::vector<LazySegmentTree> yo(
      n, LazySegmentTree(std::vector<long long>(n, 1)));
  std::vector<LazySegmentTree> ta(
      n, LazySegmentTree(std::vector<long long>(n, 1)));
  long long ans = 0;
  for (int i = 0; i < (int)(n * n); i++) {
    p[i]--;
    long long x = p[i] % n;
    long long y = p[i] / n;
    long long dum = INF;
    yo[y].add(x, x + 1, -1);
    ta[x].add(y, y + 1, -1);
    chmin(dum, yo[y].getsum(0ll, x));
    chmin(dum, yo[y].getsum(x, n));
    chmin(dum, ta[x].getsum(0ll, y));
    chmin(dum, ta[x].getsum(y, n));
    ans += dum;
  }
  std::cout << ans << std::endl;
}
