#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll mod = 1000000007;
const double eps = 1e-8;
const int MAX_V = 3000;
const int INF = 1e9;
const int dx[4] = {-1, 1, 0, 0};
const int dy[4] = {0, 0, 1, -1};
struct Edge {
  int to;
  ll cost;
};
vector<Edge> G[MAX_V];
ll dijkstra(int s, int t) {
  vector<ll> d(MAX_V, INF);
  priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>>
      q;
  q.push(pair<ll, int>(0, s));
  while (!q.empty()) {
    pair<ll, int> p = q.top();
    q.pop();
    if (d[p.second] <= p.first) continue;
    d[p.second] = p.first;
    for (Edge &e : G[p.second]) {
      if (d[e.to] > p.first + e.cost) {
        q.push(pair<ll, int>(p.first + e.cost, e.to));
      }
    }
  }
  return d[t];
}
int main() {
  int N;
  cin >> N;
  vector<int> p(N * N);
  for (int i = 0; i < N * N; ++i) {
    cin >> p[i];
    p[i]--;
  }
  function<bool(int, int)> valid = [&](int y, int x) {
    return 0 <= y && y < N && 0 <= x && x < N;
  };
  vector<vector<int>> edge_i(N * N, vector<int>(N * N));
  const int T = 2999;
  for (int i = 0; i < N; ++i) {
    for (int j = 0; j < N; ++j) {
      if (i == 0 || i == N - 1 || j == 0 || j == N - 1) {
        G[i * N + j].push_back((Edge){T, 0});
      }
      for (int k = 0; k < 4; ++k) {
        int i2 = i + dy[k];
        int j2 = j + dx[k];
        if (valid(i2, j2)) {
          G[i * N + j].push_back((Edge){i2 * N + j2, 1});
          edge_i[i * N + j][i2 * N + j2] = (int)G[i * N + j].size() - 1;
        }
      }
    }
  }
  ll res = 0;
  for (int i = 0; i < N * N; ++i) {
    res += dijkstra(p[i], T);
    for (int j = 0; j < 4; ++j) {
      int i2 = p[i] / N + dy[j];
      int j2 = p[i] % N + dx[j];
      if (valid(i2, j2)) {
        int ei = edge_i[i2 * N + j2][p[i]];
        G[i2 * N + j2][ei].cost = 0;
      }
    }
  }
  cout << res << endl;
  return 0;
}
