#include <bits/stdc++.h>
using namespace std;
const int N = 510;
int n;
pair<int, int> pos[N * N];
int p[N * N];
int X[4] = {1, -1, 0, 0}, Y[4] = {0, 0, 1, -1};
pair<int, int> f[N][N];
int u[N][N], d[N][N], l[N][N], r[N][N];
bool vis[N][N];
pair<int, int> find_f(int x, int y) {
  if (f[x][y] == make_pair(x, y)) return {x, y};
  int xx = f[x][y].first, yy = f[x][y].second;
  u[xx][yy] = min(u[xx][yy], u[x][y]);
  d[xx][yy] = max(d[xx][yy], d[x][y]);
  l[xx][yy] = min(l[xx][yy], l[x][y]);
  r[xx][yy] = max(r[xx][yy], r[x][y]);
  return f[x][y] = find_f(xx, yy);
}
int solve(int id) {
  int x = pos[id].first, y = pos[id].second;
  vis[x][y] = true;
  auto t = find_f(x, y);
  int fx = t.first, fy = t.second;
  for (int i = 0; i < 4; i++) {
    int xx = x + X[i], yy = y + Y[i];
    if (xx >= 1 && xx <= n && yy >= 1 && yy <= n && vis[xx][yy]) {
      auto t = find_f(xx, yy);
      int fxx = t.first, fyy = t.second;
      f[fxx][fyy] = {fx, fy};
      u[fx][fy] = min(u[fx][fy], u[fxx][fyy]);
      d[fx][fy] = max(d[fx][fy], d[fxx][fyy]);
      l[fx][fy] = min(l[fx][fy], l[fxx][fyy]);
      r[fx][fy] = max(r[fx][fy], r[fxx][fyy]);
    }
  }
  return min(u[fx][fy] - 1,
             min(n - d[fx][fy], min(l[fx][fy] - 1, n - r[fx][fy])));
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  int tot = 0;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      tot++;
      pos[tot] = {i, j};
      f[i][j] = {i, j};
      u[i][j] = i;
      d[i][j] = i;
      l[i][j] = j;
      r[i][j] = j;
    }
  }
  int ans = 0;
  for (int i = 1; i <= n * n; i++) {
    cin >> p[i];
    ans += solve(p[i]);
  }
  cout << ans;
  getchar();
  getchar();
  return 0;
}
