#include <bits/stdc++.h>
using namespace std;
const int N = 500 * 500 + 1;
struct Data {
  int d, u, l, r;
  Data(int row = 0, int col = 0) {
    d = u = row;
    l = r = col;
  }
  void optimize(Data X) {
    d = max(d, X.d);
    u = min(u, X.u);
    l = min(l, X.l);
    r = max(r, X.r);
  }
} a[N];
int n, root[N], dd[501][501];
map<int, pair<long long, long long> > ma;
int f(int i, int j) { return (i - 1) * n + j; }
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};
void Union(int q, int p) {
  root[q] = p;
  a[p].optimize(a[q]);
}
int getroot(int u) { return (root[u] ? root[u] = getroot(root[u]) : u); }
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  if (fopen(".inp", "r")) freopen(".inp", "r", stdin);
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= n; ++j) {
      int decode = f(i, j);
      ma[decode] = make_pair(i, j);
      a[decode] = Data(i, j);
    }
  }
  long long ans = 0;
  for (int i = 1; i <= n * n; ++i) {
    int decode;
    cin >> decode;
    auto P = ma[decode];
    int row = P.first, col = P.second;
    dd[row][col] = 1;
    for (int d = 0; d < 4; ++d) {
      int xx = row + dx[d];
      int yy = col + dy[d];
      if (xx < 1 || xx > n || yy < 1 || yy > n || dd[xx][yy] == 0) continue;
      int ver = f(xx, yy);
      int p = getroot(decode);
      int q = getroot(ver);
      if (p == q) continue;
      Union(p, q);
    }
    int ROOT = getroot(decode);
    ans += min({a[ROOT].l - 1, n - a[ROOT].r, n - a[ROOT].d, a[ROOT].u - 1});
  }
  cout << ans;
  return 0;
}
