#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long long inf = 1LL << 61;
int main() {
  long long n;
  cin >> n;
  vector<long long> p(n * n);
  for (long long i = 0; i < n * n; i++) {
    cin >> p[i];
    p[i]--;
  }
  vector<long long> d(n * n, -1);
  queue<pair<long long, long long> > q;
  for (long long i = 0; i < n; i++) {
    q.push({i * n, 0});
    q.push({i * n + n - 1, 0});
    q.push({i, 0});
    q.push({n * (n - 1) + i, 0});
  }
  while (q.size()) {
    long long id = q.front().first;
    long long td = q.front().second;
    q.pop();
    if (d[id] > -1) continue;
    d[id] = td;
    if (id + 1 < n * n) q.push({id + 1, td + 1});
    if (id - 1 > -1) q.push({id - 1, td + 1});
    if (id + n < n * n) q.push({id + n, td + 1});
    if (id - n > -1) q.push({id - n, td + 1});
  }
  long long ans = 0;
  set<long long> al;
  for (long long i = 0; i < n * n; i++) {
    long long id = p[i];
    ans += d[id];
    q.push({id, d[id] - 1});
    while (q.size()) {
      long long tid = q.front().first;
      long long td = q.front().second;
      q.pop();
      if (td >= d[tid]) continue;
      if (!al.count(tid)) {
        d[tid] = td;
        td++;
      } else
        al.insert(tid);
      if (tid + 1 < n * n) q.push({tid + 1, td});
      if (tid - 1 > -1) q.push({tid - 1, td});
      if (tid + n < n * n) q.push({tid + n, td});
      if (tid - n > -1) q.push({tid - n, td});
    }
    al.insert(id);
    d[id]++;
  }
  cout << ans << endl;
}
