#include <bits/stdc++.h>
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
using namespace std;
const long long maxn = 5e2 + 100;
const long long inf = 1e9;
long long n, m, k, t;
bool used[maxn][maxn][maxn];
long long dp[maxn][maxn][maxn];
long long I[maxn][maxn];
vector<pair<long long, long long>> go{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
bool in(long long first, long long second) {
  return first >= 0 && second >= 0 && first < n && second < n;
}
pair<long long, long long> get_coord(long long c) {
  long long first = c / n, second = c % n;
  return make_pair(first, second);
}
long long geti(long long first, long long second) { return first * n + second; }
long long getdp(long long first, long long second, long long h) {
  if (used[first][second][h]) {
    return dp[first][second][h];
  }
  long long q;
  dp[first][second][h] = inf;
  used[first][second][h] = 1;
  for (auto p : go) {
    long long x1 = first + p.first, y1 = second + p.second;
    if (!in(x1, y1)) {
      continue;
    }
    if (h != 0) {
      long long dans1 = getdp(x1, y1, h - 1);
      dp[first][second][h] = min(dp[first][second][h], dans1);
    }
  }
  return dp[first][second][h];
}
void getdp1(long long first, long long second, long long h) {
  for (auto p : go) {
    long long x1 = first + p.first, y1 = second + p.second;
    if (!in(x1, y1)) {
      continue;
    }
    long long dans2 = max(dp[x1][y1][h], I[x1][y1]);
    dp[first][second][h] = min(dp[first][second][h], dans2);
  }
}
int main() {
  ios_base ::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  long long q, w, e, a, b, c;
  cin >> n;
  vector<long long> A(n * n);
  for (q = 0; q < n * n; q++) {
    cin >> A[q];
    A[q]--;
    pair<long long, long long> p = get_coord(A[q]);
    I[p.first][p.second] = q;
  }
  queue<pair<long long, long long>> Q;
  for (q = 0; q < n; q++) {
    for (w = 0; w < n; w++) {
      if (q == 0 || w == 0 || q == n - 1 || w == n - 1) {
        for (e = 0; e <= n; e++) {
          used[q][w][e] = 1;
        }
      }
    }
  }
  for (e = 0; e <= n; e++) {
    for (q = 0; q < n; q++) {
      for (w = 0; w < n; w++) {
        getdp(q, w, e);
      }
    }
    vector<pair<long long, pair<long long, long long>>> P;
    for (q = 0; q < n; q++) {
      for (w = 0; w < n; w++) {
        P.push_back(make_pair(dp[q][w][e], make_pair(q, w)));
      }
    }
    sort(P.begin(), P.end());
    for (auto p : P) {
      long long first = p.second.first, second = p.second.second;
      getdp1(first, second, e);
    }
  }
  long long ans = 0;
  for (q = 0; q < n; q++) {
    for (w = 0; w < n; w++) {
      for (e = 0; e <= n; e++) {
        if (dp[q][w][e] <= I[q][w]) {
          ans += e;
          break;
        }
      }
    }
  }
  cout << ans;
  return 0;
}
