#include <bits/stdc++.h>
using namespace std;
constexpr double EPS = 1e-9;
constexpr int INF = 1001001001;
constexpr int mod = 1000000007;
constexpr int dx[4] = {1, 0, -1, 0};
constexpr int dy[4] = {0, 1, 0, -1};
int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int n;
  cin >> n;
  int sz = n * n;
  vector<int> p(sz);
  for (int i = 0; i < sz; ++i) cin >> p[i];
  vector<pair<int, int>> pos(sz + 1);
  int cur = 1;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
      pos[cur++] = pair<int, int>(i, j);
    }
  }
  int ans = 0;
  vector<vector<int>> board(n, vector<int>(n, 0));
  for (int i = sz - 1; i >= 0; --i) {
    int sx = pos[p[i]].first, sy = pos[p[i]].second;
    if (sx == 0 || sx == n - 1 || sy == 0 || sy == n - 1) {
      board[sx][sy] = p[i];
      continue;
    }
    vector<vector<int>> dist(n, vector<int>(n, INF));
    deque<pair<int, int>> deq;
    dist[sx][sy] = 0;
    deq.push_back(pair<int, int>(sx, sy));
    int mindist = INF;
    bool ok = false;
    while (!deq.empty()) {
      pair<int, int> point = deq.front();
      deq.pop_front();
      int x = point.first, y = point.second;
      if (x == 0 || x == n - 1 || y == 0 || y == n - 1) {
        mindist = min(mindist, dist[x][y]);
        break;
      }
      for (int j = 0; j < 4; ++j) {
        int nx = x + dx[j], ny = y + dy[j];
        if (board[nx][ny] > 0) {
          if (dist[nx][ny] > dist[x][y] + 1) {
            dist[nx][ny] = dist[x][y] + 1;
            deq.push_back(pair<int, int>(nx, ny));
          }
        } else {
          if (dist[nx][ny] > dist[x][y]) {
            dist[nx][ny] = dist[x][y];
            deq.push_front(pair<int, int>(nx, ny));
          }
        }
      }
    }
    board[sx][sy] = p[i];
    ans += mindist;
  }
  cout << ans << endl;
}
