#include <bits/stdc++.h>
using namespace std;
set<int> a[250010], b[250010];
int mem[250010], par[250010];
int pa(int x) {
  if (x == par[x]) {
    return x;
  }
  return par[x] = pa(par[x]);
}
void join(int x, int y) {
  int tmp1 = pa(x), tmp2 = pa(y);
  if (tmp1 == tmp2) {
    return;
  }
  int sz1 = a[tmp1].size(), sz2 = a[tmp2].size();
  int mn = min(mem[tmp1], mem[tmp2]);
  if (sz1 > sz2) {
    for (auto it : a[tmp2]) {
      if (it != x && mem[pa(it)]) a[tmp1].insert(pa(it));
    }
    par[tmp2] = tmp1;
    mem[tmp1] = mn;
    a[tmp1].erase(tmp2);
  } else {
    for (auto it : a[tmp1]) {
      if (it != y && mem[pa(it)]) a[tmp2].insert(pa(it));
    }
    par[tmp1] = tmp2;
    mem[tmp2] = mn;
    a[tmp2].erase(tmp1);
  }
}
bool l[250010];
int nxt;
void dfs(int x, int val) {
  deque<pair<int, int>> q;
  mem[x] = val;
  vector<int> v;
  for (auto it : a[x]) {
    if (mem[it] == 0) {
      v.push_back(it);
    }
    if (l[x]) {
      if (mem[it] > val) q.push_front(make_pair(-val, it));
    } else {
      if (mem[it] > val + 1) q.push_back(make_pair(-val - 1, it));
    }
  }
  for (auto it : v) {
    a[x].erase(it);
  }
  pair<int, int> tmp;
  while (!q.empty()) {
    tmp = q.front();
    q.pop_front();
    if (mem[tmp.second] <= -tmp.first) {
      continue;
    }
    mem[tmp.second] = -tmp.first;
    vector<int> v;
    for (auto it : a[tmp.second]) {
      if (mem[it] == 0) {
        v.push_back(it);
      }
      if (l[tmp.second]) {
        if (mem[it] > tmp.first) q.push_front(make_pair(tmp.first, it));
      } else {
        if (mem[it] > tmp.first + 1) q.push_back(make_pair(tmp.first - 1, it));
      }
    }
    for (auto it : v) {
      a[tmp.second].erase(it);
    }
  }
}
int p[250010];
int main() {
  int n;
  while (cin >> n) {
    long long ans = 0;
    for (int i = 0; i < n * n; ++i) {
      scanf("%d", p + i);
    }
    int tmp;
    for (int i = 0; i < n; ++i) {
      for (int j = 1; j <= n; ++j) {
        tmp = i * n + j;
        mem[tmp] = min(min(i, j - 1), min(n - i - 1, n - j));
        par[tmp] = tmp;
        if (i - 1 >= 0) {
          a[tmp].insert((i - 1) * n + j);
          b[tmp].insert((i - 1) * n + j);
        }
        if (i + 1 < n) {
          a[tmp].insert((i + 1) * n + j);
          b[tmp].insert((i + 1) * n + j);
        }
        if (j + 1 <= n) {
          a[tmp].insert(i * n + j + 1);
          b[tmp].insert(i * n + j + 1);
        }
        if (j - 1 >= 1) {
          a[tmp].insert(i * n + j - 1);
          b[tmp].insert(i * n + j - 1);
        }
      }
    }
    for (int i = 0; i < n * n; ++i) {
      ans += mem[p[i]];
      int tmp = mem[p[i]];
      for (auto it : b[p[i]]) {
        if (l[it]) {
          join(it, p[i]);
        }
      }
      l[p[i]] = 1;
      nxt = p[i + 1];
      if (tmp >= mem[pa(p[i])] && i + 1 < n * n) dfs(pa(p[i]), mem[pa(p[i])]);
    }
    printf("%lld\n", ans);
  }
  return 0;
}
