#include <bits/stdc++.h>
using namespace std;
long long n, h, w, r[500][500] = {0}, D[500][500];
char C[500][500];
priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>,
               greater<pair<int, pair<int, int>>>>
    X, emptyy;
int vx[4] = {0, 1, 0, -1}, vy[4] = {1, 0, -1, 0};
long long bfs(int sx, int sy) {
  long long ans = 1e18;
  swap(X, emptyy);
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < n; j++) r[i][j] = 0;
  r[sx][sy] = 1;
  X.push(make_pair(1, make_pair(sx, sy)));
  while (X.size()) {
    pair<int, pair<int, int>> a = X.top();
    X.pop();
    for (long long i = 0; i < 4; i++) {
      int nx = a.second.first + vx[i], ny = a.second.second + vy[i];
      if (nx >= 0 && nx < n && ny >= 0 && ny < n && r[nx][ny] == 0) {
        if (C[nx][ny] == '#')
          r[nx][ny] = a.first + 1,
          X.push(make_pair(r[nx][ny], make_pair(nx, ny)));
        else
          r[nx][ny] = a.first, X.push(make_pair(r[nx][ny], make_pair(nx, ny)));
      }
    }
  }
  for (long long i = 0; i < n; i++)
    ans = min({ans, r[i][0], r[0][i], r[n - 1][i], r[i][n - 1]});
  return ans;
}
int main() {
  int pair<long long, long long>[250001];
  long long ans = 0;
  cin >> n;
  h = n, w = n;
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < n; j++) C[i][j] = '.';
  for (long long i = 0; i < n * n; i++) cin >> pair<long long, long long>[i];
  reverse(pair<long long, long long>, pair<long long, long long> + n * n);
  for (long long i = 0; i < n * n; i++) {
    long long a = bfs((pair<long long, long long>[i] - 1) / n,
                      (pair<long long, long long>[i] + n - 1) % n);
    ans += a - 1;
    C[(pair<long long, long long>[i] - 1) / n]
     [(pair<long long, long long>[i] - 1 + n) % n] = '#';
  }
  cout << ans;
}
