#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int N;
vector<int> order;
vector<vector<int>> P, D;
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
int dijkstra(int n) {
  using pi = pair<int, int>;
  priority_queue<pi, vector<pi>, greater<pi>> Q;
  Q.push({0, order[n]});
  int ret = 1 << 28;
  while (!Q.empty()) {
    auto q = Q.top();
    Q.pop();
    int x = q.second / N;
    int y = q.second % N;
    if (x == 0 || x == N - 1 || y == 0 || y == N - 1) ret = min(ret, D[x][y]);
    if (D[x][y] < q.first) continue;
    for (int i = 0; i < (int)(4); i++) {
      int nx = x + dx[i];
      int ny = y + dy[i];
      if (nx < 0 || nx >= N || ny < 0 || ny >= N) continue;
      if (D[nx][ny] > q.first + (P[nx][ny] > (n + 1))) {
        D[nx][ny] = q.first + (P[nx][ny] > (n + 1));
        Q.push({D[nx][ny], nx * N + ny});
      }
    }
  }
  return ret;
}
int main() {
  cin >> N;
  order.assign(N * N, 0);
  P.assign(N, vector<int>(N));
  for (int i = 0; i < (int)(N * N); i++) {
    int p;
    cin >> p;
    p--;
    P[p / N][p % N] = i + 1;
    order[i] = p;
  }
  int ans = 0;
  for (int i = 0; i < (int)(N * N); i++) {
    D.assign(N, vector<int>(N, 1 << 28));
    D[order[i] / N][order[i] % N] = 0;
    int d = dijkstra(i);
    ans += d;
  }
  cout << ans << endl;
  return 0;
}
