#include <bits/stdc++.h>
using namespace std;
const int MID = 505 * 505;
const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, -1, 0, 1};
int n, m, i, j, e, x, y, nx, ny, cur, nxt, fi, fr, q[MID * 2], a[MID], d[MID],
    v[MID], p[MID], pr[505][505], rmcnt, rm[MID], sbst[MID];
unordered_set<int> g[MID];
long long r;
int fs(int x) {
  if (p[x] != x) p[x] = fs(p[x]);
  return p[x];
}
int un(int i, int j) {
  if (g[i].size() < g[j].size()) {
    for (auto it = g[i].begin(); it != g[i].end(); it++) g[j].insert(*it);
    p[i] = j;
    return j;
  }
  for (auto it = g[j].begin(); it != g[j].end(); it++) g[i].insert(*it);
  p[j] = i;
  return i;
}
int main() {
  scanf("%d", &n);
  m = n * n;
  for (i = 1; i <= m; i++) scanf("%d", &a[i]);
  for (i = 1; i <= n; i++)
    for (j = 1; j <= n; j++) {
      cur = (i - 1) * n + j;
      pr[i][j] = cur;
      p[cur] = cur;
      v[cur] = 1;
    }
  for (i = 0; i <= n; i++)
    for (j = 0; j <= n; j++) {
      cur = fs(pr[i][j]);
      for (e = 2; e < 4; e++) {
        nx = i + dx[e];
        ny = j + dy[e];
        nxt = fs(pr[nx][ny]);
        if (cur != nxt) {
          g[cur].insert(nxt);
          g[nxt].insert(cur);
        }
      }
    }
  q[fi = MID] = 0;
  for (fr = MID + 1; fi < fr;) {
    x = q[fi++];
    for (auto it = g[x].begin(); it != g[x].end(); it++) {
      y = *it;
      if (d[y] == 0 && y > 0) {
        d[y] = d[x] + v[y];
        if (v[y])
          q[fr++] = y;
        else
          q[--fi] = y;
      }
    }
  }
  for (i = 1; i <= m; i++) {
    x = (a[i] - 1) / n + 1;
    y = (a[i] - 1) % n + 1;
    cur = fs(pr[x][y]);
    --d[cur];
    r += d[cur];
    v[cur] = 0;
    for (e = 0; e < 4; e++) {
      nx = x + dx[e];
      ny = y + dy[e];
      nxt = fs(pr[nx][ny]);
      if (v[nxt] == 0 && cur != nxt) cur = un(cur, nxt);
    }
    q[fi = MID] = cur;
    for (fr = MID + 1; fi < fr;) {
      x = q[fi++];
      rmcnt = 0;
      for (auto it = g[x].begin(); it != g[x].end(); it++) {
        cur = fs(*it);
        if (*it != cur) {
          sbst[rmcnt] = cur;
          rm[rmcnt++] = *it;
        }
      }
      for (j = 0; j < rmcnt; j++) {
        g[x].erase(rm[j]);
        g[x].insert(sbst[j]);
      }
      for (auto it = g[x].begin(); it != g[x].end(); it++) {
        y = *it;
        if (d[y] > d[x] + v[y]) {
          d[y] = d[x] + v[y];
          if (v[y])
            q[fr++] = y;
          else
            q[--fi] = y;
        }
      }
    }
  }
  printf("%lld\n", r);
  return 0;
}
