#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const long long INF_LL = 1e18 + 3;
const int INF_int = 1e9 + 3;
int main() {
  int n;
  cin >> n;
  int arr[n * n];
  for (int i = 0; i < n * n; i++) cin >> arr[i];
  bool field[n + 2][n + 2];
  for (int i = 0; i < n + 2; i++)
    for (int j = 0; j < n + 2; j++) {
      if (i == 0 || i == n + 1 || j == 0 || j == n + 1)
        field[i][j] = true;
      else
        field[i][j] = false;
    }
  int memo[n + 2][n + 2];
  for (int i = 0; i < n + 2; i++)
    for (int j = 0; j < n + 2; j++) {
      if (i == 0 || i == n + 1 || j == 0 || j == n + 1)
        memo[i][j] = 0;
      else
        memo[i][j] = INF_int;
    }
  long long ans = 0;
  for (int i = 0; i < n * n; i++) {
    int now = arr[i];
    int sy = (now + n - 1) / n;
    int am = (now) % n;
    if (am == 0) am += n;
    queue<pair<int, int>> que;
    que.push(make_pair(sy, am));
    bool visited[n][n];
    for (int j = 0; j < n; j++)
      for (int k = 0; k < n; k++) visited[j][k] = false;
    visited[sy][am] = true;
    int dx[4] = {1, -1, 0, 0};
    int dy[4] = {0, 0, 1, -1};
    bool ffl = false;
    int tmpans = 0;
    while (!que.empty()) {
      queue<pair<int, int>> que2;
      while (!que.empty()) {
        pair<int, int> now = que.front();
        que.pop();
        int x = now.first;
        int y = now.second;
        visited[x][y] = true;
        for (int j = 0; j < 4; j++) {
          if (field[x + dx[j]][y + dy[j]] && !visited[x + dx[j]][y + dy[j]]) {
            if (memo[x + dx[j]][y + dy[j]] == 0) {
              ffl = true;
              break;
            }
            que.push(make_pair(x + dx[j], y + dy[j]));
          } else if (!field[x + dx[j]][y + dy[j]]) {
            que2.push(make_pair(x + dx[j], y + dy[j]));
          }
        }
        if (ffl) break;
      }
      if (ffl) break;
      tmpans++;
      que = que2;
    }
    ans += tmpans;
    field[sy][am] = true;
    if (tmpans == 0) memo[sy][am] = 0;
  }
  cout << ans << endl;
}
