#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
using vl = vector<ll>;
using Map = map<ll, ll>;
using T = tuple<ll, ll, ll>;
using vvl = vector<vector<ll>>;
template <typename T>
bool chmax(T &a, const T &b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <typename T>
bool chmin(T &a, const T &b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}
const ll INF = 1LL << 60;
const ll MOD = 1000000007;
ll N;
ll F(ll x, ll y) { return N * x + y + 1; }
int main() {
  cin >> N;
  ll ans = 0;
  vector<ll> Pa(N * N, 0);
  for (ll i = 0; i < N * N; i++) cin >> Pa[i];
  vector<vector<P>> G(N * N + 1, vector<P>(0));
  for (ll i = 1; i <= N * N; i++) {
    if (i % N == 0 || i % N == 1 || i <= N || i >= N * N - N + 1)
      G[0].emplace_back(P(0, i));
  }
  for (ll i = 1; i < N * N; i++) {
    ll x = (i - 1) % N;
    ll y = (i - 1) / N;
    if (x > 0) G[i].emplace_back(P(1, F(x - 1, y)));
    if (x < N - 1) G[i].emplace_back(P(1, F(x + 1, y)));
    if (y > 0) G[i].emplace_back(P(1, F(x, y - 1)));
    if (y < N - 1) G[i].emplace_back(P(1, F(x, y + 1)));
  }
  priority_queue<P, vector<P>, greater<P>> pq;
  vector<ll> d(N * N + 1, INF);
  d[0] = 0;
  pq.emplace(P(0, 0));
  while (!pq.empty()) {
    P x = pq.top();
    pq.pop();
    ll y = x.first;
    ll z = x.second;
    if (y > d[z]) continue;
    for (auto p : G[z]) {
      ll to = p.second;
      ll cost = p.first;
      if (d[to] > d[z] + cost) {
        d[to] = d[z] + cost;
        pq.emplace(P(d[to], to));
      }
    }
  }
  for (ll i = 0; i < N * N; i++) {
    ll s = d[Pa[i]];
    ans += s;
    ll x = (Pa[i] - 1) % N;
    ll y = (Pa[i] - 1) / N;
    if (x > 0) G[Pa[i]].emplace_back(P(0, F(x - 1, y)));
    if (x < N - 1) G[Pa[i]].emplace_back(P(0, F(x + 1, y)));
    if (y > 0) G[Pa[i]].emplace_back(P(0, F(x, y - 1)));
    if (y < N - 1) G[Pa[i]].emplace_back(P(0, F(x, y + 1)));
    if (x > 0) G[F(x - 1, y)].emplace_back(P(0, Pa[i]));
    if (x < N - 1) G[F(x + 1, y)].emplace_back(P(0, Pa[i]));
    if (y > 0) G[F(x, y - 1)].emplace_back(P(0, Pa[i]));
    if (y < N - 1) G[F(x, y + 1)].emplace_back(P(0, Pa[i]));
    pq.push(P(s, Pa[i]));
    while (!pq.empty()) {
      P x = pq.top();
      pq.pop();
      ll y = x.first;
      ll z = x.second;
      if (y > d[z]) continue;
      for (auto p : G[z]) {
        ll to = p.second;
        ll cost = p.first;
        if (d[to] > d[z] + cost) {
          d[to] = d[z] + cost;
          pq.emplace(P(d[to], to));
        }
      }
    }
  }
  return 0;
}
