#include <bits/stdc++.h>
using namespace std;
int dis[505 * 505];
int inp[505 * 505];
int ix[505 * 505];
int jy[505 * 505];
int vis[505 * 505];
int main() {
  int n;
  cin >> n;
  deque<int> dq;
  for (int i = 1; i <= n * n; i++) {
    int x;
    cin >> x;
    inp[x] = i;
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      int v = (i - 1) * n + j;
      dis[v] = 1e9;
      ix[v] = i;
      jy[v] = j;
      if (i == 1 or j == 1 or i == n or j == n) {
        dq.push_back(v);
        dis[v] = 0;
        vis[v] = 1;
      }
    }
  }
  while (!dq.empty()) {
    int x = dq.front();
    dq.pop_front();
    int i = ix[x];
    int j = jy[x];
    if (i != 1) {
      int ii = i - 1;
      int jj = j;
      int y = (ii - 1) * n + jj;
      if (!vis[y]) {
        if (inp[x] < inp[y]) {
          dq.push_front(y);
          dis[y] = min(dis[y], dis[x]);
        } else {
          dq.push_back(y);
          dis[y] = min(dis[y], dis[x] + 1);
        }
        vis[y] = 1;
      }
    }
    if (i != n) {
      int ii = i + 1;
      int jj = j;
      int y = (ii - 1) * n + jj;
      if (!vis[y]) {
        if (inp[x] < inp[y]) {
          dq.push_front(y);
          dis[y] = min(dis[y], dis[x]);
        } else {
          dq.push_back(y);
          dis[y] = min(dis[y], dis[x] + 1);
        }
        vis[y] = 1;
      }
    }
    if (j != 1) {
      int ii = i;
      int jj = j - 1;
      int y = (ii - 1) * n + jj;
      if (!vis[y]) {
        if (inp[x] < inp[y]) {
          dq.push_front(y);
          dis[y] = min(dis[y], dis[x]);
        } else {
          dq.push_back(y);
          dis[y] = min(dis[y], dis[x] + 1);
        }
        vis[y] = 1;
      }
    }
    if (j != n) {
      int ii = i;
      int jj = j + 1;
      int y = (ii - 1) * n + jj;
      if (!vis[y]) {
        if (inp[x] < inp[y]) {
          dq.push_front(y);
          dis[y] = min(dis[y], dis[x]);
        } else {
          dq.push_back(y);
          dis[y] = min(dis[y], dis[x] + 1);
        }
        vis[y] = 1;
      }
    }
  }
  int ans = 0;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      int v = (i - 1) * n + j;
    }
  }
  for (int i = 1; i <= n * n; i++) {
    ans += dis[i];
  }
  cout << ans << endl;
  return 0;
}
