#include <bits/stdc++.h>
using namespace std;
using lint = long long;
const lint inf = 1LL << 60;
const lint mod = 1000000007;
struct UnionFind {
  vector<int> rank, parent, size;
  UnionFind(int n) : rank(n + 1, 0), parent(n + 1), size(n + 1, 1) {
    iota(parent.begin(), parent.end(), 0);
  }
  int root(int x) {
    if (x != parent[x]) {
      parent[x] = root(parent[x]);
    }
    return parent[x];
  }
  bool isSame(int x, int y) { return root(x) == root(y); }
  bool unite(int x, int y) { return link(root(x), root(y)); }
  bool link(int x, int y) {
    if (x == y) return false;
    if (rank[x] > rank[y]) {
      parent[y] = x;
      size[x] += size[y];
    } else {
      parent[x] = y;
      size[y] += size[x];
      if (rank[x] == rank[y]) {
        rank[y]++;
      }
    }
    return true;
  }
  int getSize(int x) { return size[root(x)]; }
};
template <class T>
bool chmax(T &a, const T &b) {
  return (a < b) ? (a = b, 1) : 0;
}
template <class T>
bool chmin(T &a, const T &b) {
  return (b < a) ? (a = b, 1) : 0;
}
int main() {
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
  int n;
  cin >> n;
  vector<int> p(n * n);
  for (int i = 0; i < n * n; ++i) {
    cin >> p[i];
    p[i]--;
  }
  vector<vector<int>> dist(n, vector<int>(n, 1000000));
  vector<vector<int>> c(n, vector<int>(n, 1));
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < n; ++j) {
      chmin(dist[i][j], 1 + abs(i));
      chmin(dist[i][j], 1 + abs(n - 1 - i));
      chmin(dist[i][j], 1 + abs(j));
      chmin(dist[i][j], 1 + abs(n - 1 - j));
    }
  }
  const int dx[4] = {-1, 1, 0, 0};
  const int dy[4] = {0, 0, -1, 1};
  auto inside = [&](int y, int x) {
    return 0 <= y && y < n - 1 && 0 <= x && x < n - 1;
  };
  UnionFind uf(n * n);
  lint ret = 0;
  for (int i = 0; i < n * n; ++i) {
    int h = p[i] / n;
    int w = p[i] % n;
    int r = uf.root(p[i]);
    int rh = r / n;
    int rw = r % n;
    c[h][w] = 0;
    int mindist = dist[rh][rw] - 1;
    for (int j = 0; j < 4; ++j) {
      int nh = h + dy[j];
      int nw = w + dx[j];
      if (inside(nh, nw)) {
        int nn = nh * n + nw;
        int ro = uf.root(nn);
        int roh = ro / n;
        int row = ro % n;
        chmin(mindist, dist[roh][row]);
        if (c[nh][nw] == 0) {
          uf.unite(p[i], nn);
        }
      }
    }
    int nr = uf.root(p[i]);
    int nrh = nr / n;
    int nrw = nr % n;
    dist[nrh][nrw] = mindist;
    ret += mindist;
  }
  cout << ret << "\n";
  return 0;
}
