#include <bits/stdc++.h>
using namespace std;
int graph[3000][3000];
int dijkstra(int s, int N) {
  int cnt = 1000000000;
  vector<int> dis((N + 2) * (N + 2), 1000000000);
  dis[s] = 0;
  priority_queue<pair<int, int>, vector<pair<int, int>>,
                 greater<pair<int, int>>>
      que;
  que.push(make_pair(dis[s], s));
  int u, v;
  while (!que.empty()) {
    u = que.top().second;
    que.pop();
    vector<int> around = {u - 1, u + 1, u + N + 2, u - N - 2};
    int x;
    for (int i = 0; i < 4; i++) {
      x = around[i];
      if (dis[x] > dis[u] + graph[u][x]) {
        dis[x] = dis[u] + graph[u][x];
        if (1 <= x % (N + 2) && x % (N + 2) <= N && N < x &&
            (N + 2) * (N + 1) > x)
          que.push(make_pair(dis[x], x));
        else {
          cnt = min(cnt, dis[x]);
        }
      }
    }
  }
  return cnt;
}
int main() {
  int N;
  cin >> N;
  for (int i = (0); i < ((N + 2) * (N + 2)); i++)
    for (int j = (0); j < ((N + 2) * (N + 2)); j++) graph[i][j] = 1;
  for (int i = (1); i < (N + 1); i++) {
    graph[i][i + N + 2] = 0;
    graph[i + N + 2][i] = 0;
    graph[(N + 2) * i][(N + 2) * i + 1] = 0;
    graph[(N + 2) * i + 1][(N + 2) * i] = 0;
    graph[N + 1 + (N + 2) * i][N + (N + 2) * i] = 0;
    graph[N + (N + 2) * i][N + 1 + (N + 2) * i] = 0;
    graph[N * N + 2 * N + i][N * N + 3 * N + i + 2] = 0;
    graph[N * N + 3 * N + i + 2][N * N + 2 * N + i] = 0;
  }
  vector<int> line(N * N);
  for (int i = 0; i < N * N; i++) {
    cin >> line[i];
  }
  int ans = 0;
  for (int i = 0; i < N * N; i++) {
    int s, t, start;
    s = (line[i] - 1) / N + 1;
    t = line[i] % N;
    start = (N + 2) * s + t;
    ans += dijkstra(start, N);
    graph[start - 1][start] = 0;
    graph[start + 1][start] = 0;
    graph[start + N + 2][start] = 0;
    graph[start - N - 2][start] = 0;
  }
  cout << ans << endl;
  return 0;
}
