#include <bits/stdc++.h>
using namespace std;
const int N = 500 + 10;
int dis[N * N];
struct edge {
  int to, next, len;
} e[N * N * 4];
int tot, m, n, first[N * N], bk[N * N], s, num[N][N];
void add(int u, int v, int d) {
  e[++tot].next = first[u], first[u] = tot;
  e[tot].len = d, e[tot].to = v;
}
queue<int> q;
void spfa() {
  q.push(0);
  dis[0] = 0;
  while (!q.empty()) {
    int now = q.front();
    q.pop();
    for (int i = first[now]; i; i = e[i].next) {
      int u = e[i].to;
      if (dis[u] > dis[now] + e[i].len) {
        dis[u] = dis[now] + e[i].len;
        if (!bk[u]) bk[u] = 1, q.push(u);
      }
    }
    bk[now] = 0;
  }
}
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
int ans;
struct point {
  int x, y;
} a[N * N];
int main() {
  scanf("%d", &n);
  int cnt = 0;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++) num[i][j] = ++cnt;
  cnt = 0;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
      int tmp = 0;
      scanf("%d", &tmp);
      a[++cnt].x = (tmp - 1) / n + 1;
      a[cnt].y = tmp - ((tmp - 1) / n) * n;
      for (int k = 0; k < 4; k++) {
        int xx = i + dx[k], yy = j + dy[k];
        if (xx < 1 || xx > n || yy < 1 || yy > n) {
          add(num[i][j], 0, 0);
          add(0, num[i][j], 0);
        }
        add(num[i][j], num[xx][yy], 1);
      }
    }
  }
  memset(dis, 0x3f3f3f3f, sizeof(dis));
  dis[0] = 0;
  q.push(s);
  spfa();
  for (int i = 1; i <= cnt; i++) {
    ans += dis[num[a[i].x][a[i].y]];
    for (int j = 0; j < 4; j++) {
      int xx = a[i].x + dx[j], yy = a[i].y + dy[j];
      if (xx < 1 || xx > n || yy < 1 || yy > n) continue;
      add(num[a[i].x][a[i].y], num[xx][yy], 0);
    }
    memset(dis, 0x3f3f3f3f, sizeof(dis));
    spfa();
  }
  cout << ans << endl;
}
