#include <bits/stdc++.h>
using namespace std;
int N;
struct pnt {
  int val;
  bool k, t;
  vector<int> e;
} g[250005];
int fa[250005], val[250005];
int getfa(int f) {
  if (fa[f] != f)
    fa[f] = getfa(f);
  else
    return f;
  return fa[f];
}
void change(int p) {
  g[p].k = true;
  if (p % N > 0 && g[p - 1].k) {
    int x = getfa(p - 1);
    fa[p] = x;
    g[x].val = min(g[x].val, g[p].val);
    g[x].e.insert(g[x].e.end(), g[p].e.begin(), g[p].e.end());
  }
  if (p % N < N - 1) {
    int x = getfa(p + 1);
    g[x].val = min(g[x].val, g[fa[p]].val);
    g[x].e.insert(g[x].e.end(), g[fa[p]].e.begin(), g[fa[p]].e.end());
    fa[p] = x;
  }
  if (p / N > 0) {
    int x = getfa(p - N);
    g[x].val = min(g[x].val, g[fa[p]].val);
    g[x].e.insert(g[x].e.end(), g[fa[p]].e.begin(), g[fa[p]].e.end());
    fa[p] = x;
  }
  if (p / N < N - 1) {
    int x = getfa(p + N);
    g[x].val = min(g[x].val, g[fa[p]].val);
    g[x].e.insert(g[x].e.end(), g[fa[p]].e.begin(), g[fa[p]].e.end());
    fa[p] = x;
  }
  return;
}
int dfs(int p, int v) {
  if (g[p].val == 0) {
    return v;
  }
  int mi = 1e9;
  int np = getfa(p);
  g[np].t = true;
  for (int i = 0; i < g[p].e.size(); i++) {
    int n = getfa(g[np].e[i]);
    if (g[n].k && !g[n].t) {
      mi = min(mi, dfs(n, v));
    } else {
      mi = min(mi, dfs(n, v + 1));
    }
  }
  g[np].t = false;
  g[np].val = min(g[np].val, mi);
  return mi;
}
int main() {
  cin >> N;
  for (int i = 0; i < N * N; i++) {
    fa[i] = i;
    g[i].val = min(min(i / N, N - (i / N) - 1), min(i % N, N - (i % N) - 1));
    if (i % N > 0) g[i].e.push_back(i - 1);
    if (i % N < N - 1) g[i].e.push_back(i + 1);
    if (i / N > 0) g[i].e.push_back(i - N);
    if (i / N < N - 1) g[i].e.push_back(i + N);
    g[i].k = false;
  }
  long long ans = 0;
  for (int i = 0; i < N * N; i++) {
    int p;
    cin >> p;
    int res = g[getfa(p)].val = dfs(p, 0);
    ans += res;
    change(p);
  }
  cout << ans << endl;
  return 0;
}
