#include <bits/stdc++.h>
using namespace std;
long long int inf = 1e9;
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
vector<vector<int> > pp;
long long int n;
long long int func(long long int x, long long int y) {
  queue<pair<long long int, pair<long long int, long long int> > > q, q1;
  q.push(pair<long long int, pair<long long int, long long int> >(
      0, pair<long long int, long long int>(x, y)));
  long long int v = pp[x][y];
  vector<vector<bool> > t(n, vector<bool>(n, false));
  t[x][y] = true;
  while (!q.empty() || !q1.empty()) {
    if (q.empty()) q.swap(q1);
    pair<long long int, pair<long long int, long long int> > now = q.front();
    pair<long long int, long long int> nn = now.second;
    if (nn.first == 0 || nn.first == n - 1 || nn.second == 0 ||
        nn.second == n - 1)
      return now.first;
    q.pop();
    t[nn.first][nn.second] = true;
    for (long long int i = 0; i < 4; i++) {
      long long int nx = nn.first + dx[i];
      long long int ny = nn.second + dy[i];
      long long int nc = now.first;
      if (t[nx][ny]) continue;
      if (pp[nx][ny] > v)
        q1.push(pair<long long int, pair<long long int, long long int> >(
            nc + 1, pair<long long int, long long int>(nx, ny)));
      else {
        q.push(pair<long long int, pair<long long int, long long int> >(
            nc, pair<long long int, long long int>(nx, ny)));
        t[nx][ny] = true;
      }
    }
  }
  return n;
}
int main() {
  cin >> n;
  vector<long long int> p(n * n);
  for (long long int i = 0; i < n * n; i++) cin >> p[i];
  for (long long int i = 0; i < n * n; i++) p[i]--;
  pp = vector<vector<int> >(n, vector<int>(n, 0));
  for (long long int i = 0; i < n * n; i++) pp[p[i] / n][p[i] % n] = i;
  long long int sum = 0;
  for (long long int i = 0; i < n * n; i++) {
    long long int x = p[i] / n;
    long long int y = p[i] % n;
    long long int f = func(x, y);
    sum += f;
  }
  cout << sum << endl;
  return 0;
}
