#include <bits/stdc++.h>
using namespace std;
const int INF = 100000001;
int maze[500][500];
int n;
int sy, sx;
int gy, gx;
int cc;
int d[507][507];
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
int bfs() {
  queue<pair<int, int> > que;
  for (int i = 0; i < (int)(n); i++) {
    for (int j = 0; j < (int)(n); j++) {
      d[i][j] = INF;
    }
  }
  que.push(pair<int, int>(sx, sy));
  d[sx][sy] = 0;
  while (que.size()) {
    pair<int, int> p = que.front();
    que.pop();
    for (int i = 0; i < (int)(4); i++) {
      int nx = p.first + dx[i], ny = p.second + dy[i];
      if (0 <= nx && nx < n && 0 <= ny && ny < n &&
          maze[nx][ny] <= maze[sx][sy] && d[nx][ny] == INF) {
        que.push(pair<int, int>(nx, ny));
        d[nx][ny] = d[p.first][p.second];
      }
      if (0 <= nx && nx < n && 0 <= ny && ny < n &&
          maze[nx][ny] > maze[sx][sy] && d[nx][ny] == INF) {
        que.push(pair<int, int>(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }
  cc = 500;
  for (int i = 0; i < (int)(n); i++) {
    cc = min(cc, d[i][0]);
    cc = min(cc, d[0][i]);
    cc = min(cc, d[i][n - 1]);
    cc = min(cc, d[n - 1][i]);
    if (cc == 0) break;
  }
  return cc;
}
int main() {
  cin >> n;
  int tmp, tmp1, tmp2;
  int bangou = 0;
  for (int i = 0; i < (int)(n); i++) {
    for (int j = 0; j < (int)(n); j++) {
      ++bangou;
      cin >> tmp;
      --tmp;
      tmp1 = tmp / n;
      tmp2 = tmp % n;
      maze[tmp1][tmp2] = bangou;
    }
  }
  int ans = 0;
  for (int i = 0; i < (int)(n); i++) {
    for (int j = 0; j < (int)(n); j++) {
      sy = j;
      sx = i;
      if (sx != 0 && sx != n - 1 && sy != 0 && sy != n - 1) {
        int res = bfs();
        ans += res;
      }
    }
  }
  cout << ans << endl;
  return 0;
}
