#include <bits/stdc++.h>
using namespace std;
int N;
int a[300001];
vector<int> v;
map<int, int> m;
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int par1[300000];
int rank1[300000];
vector<int> G[360001];
void init(int n) {
  for (int i = 0; i < n; i++) {
    par1[i] = i;
    rank1[i] = 0;
  }
}
int find(int x) {
  if (par1[x] == x) {
    return x;
  } else {
    return par1[x] = find(par1[x]);
  }
}
void unite(int x, int y) {
  x = find(x);
  y = find(y);
  if (x == y) return;
  if (rank1[x] < rank1[y]) {
    par1[x] = y;
    for (int i = 0; i < (G[x].size()); i++) {
      G[y].push_back(find(G[x][i]));
    }
    sort(G[y].begin(), G[y].end());
    G[y].erase(unique(G[y].begin(), G[y].end()), G[y].end());
  } else {
    par1[y] = x;
    for (int i = 0; i < (G[y].size()); i++) {
      G[x].push_back(find(G[y][i]));
    }
    sort(G[x].begin(), G[x].end());
    G[x].erase(unique(G[x].begin(), G[x].end()), G[x].end());
    rank1[x]++;
  }
}
bool same(int x, int y) { return find(x) == find(y); }
void bfs(int pre, int now, int p) {
  int nnn = pre;
  for (int i = 0; i < (G[nnn].size()); i++) {
    int aa = find(G[nnn][i]);
    int nxt = now;
    if (m[pre] > m[p]) nxt++;
    if (a[aa] > nxt) {
      a[aa] = nxt;
      bfs(aa, nxt, p);
    }
  }
}
int main() {
  cin >> N;
  init(N + 10);
  for (int i = 0; i < (N * N); i++) {
    int aa;
    cin >> aa;
    aa--;
    v.push_back(aa);
    m[aa] = i;
  }
  for (int i = 0; i < (N); i++) {
    for (int j = 0; j < (N); j++) {
      a[j * N + i] = min(i, min(j, min(N - 1 - i, N - 1 - j)));
      int now = j * N + i;
      if (i != 0) {
        G[now].push_back(now - 1);
      }
      if (i != N - 1) {
        G[now].push_back(now + 1);
      }
      if (j != 0) {
        G[now].push_back(now - N);
      }
      if (j != N - 1) {
        G[now].push_back(now + N);
      }
    }
  }
  long long ans = 0;
  for (int i = 0; i < (v.size()); i++) {
    int now = v[i];
    bfs(now, a[now], v[i]);
    ans += a[now];
    for (int i = 0; i < (G[now].size()); i++) {
      if (m[now] > m[G[now][i]]) {
        unite(G[now][i], now);
      }
    }
  }
  cout << ans << endl;
}
