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