#include <bits/stdc++.h>
using namespace std;
struct unionFind {
  int* par;
  int* rank;
  int* scale;
  unionFind(int n);
  ~unionFind();
  int find(int x);
  void unite(int x, int y);
  bool same(int x, int y);
  int size(int x);
};
unionFind::unionFind(int n) {
  par = new int[n];
  rank = new int[n];
  scale = new int[n];
  for (int i = 0; i < n; i++) {
    par[i] = i;
    rank[i] = 0;
    scale[i] = 1;
  }
}
unionFind::~unionFind() { delete[] par, rank, scale; }
int unionFind::find(int x) {
  if (par[x] == x) return x;
  return par[x] = find(par[x]);
}
void unionFind::unite(int x, int y) {
  x = find(x);
  y = find(y);
  if (x == y) return;
  if (rank[x] < rank[y]) {
    par[x] = y;
    scale[y] += scale[x];
  } else {
    par[y] = x;
    scale[x] += scale[y];
    if (rank[x] == rank[y]) rank[x]++;
  }
}
bool unionFind::same(int x, int y) { return find(x) == find(y); }
int unionFind::size(int x) {
  x = find(x);
  return scale[x];
}
int const vec1[4] = {0, -1, 0, 1};
int const vec2[4] = {1, 0, -1, 0};
int N;
int P[500];
int G[500][500];
int main() {
  cin >> N;
  for (int i = 0; i < N * N; i++) {
    cin >> P[i];
    P[i]--;
  }
  unionFind uf(N * N + 1);
  for (int i = 0; i < N; i++) fill(G[i], G[i] + N, 1);
  int ans = 0;
  for (int n = 0; n < N * N; n++) {
    int i = P[n] / N;
    int j = P[n] % N;
    G[i][j] = 0;
    for (int k = 0; k < 4; k++) {
      int i1 = i + vec1[k];
      int j1 = j + vec2[k];
      if (i1 == -1 || i1 == N || j1 == -1 || j1 == N) {
        uf.unite(0, P[n] + 1);
      } else {
        int x = i1 * N + j1 + 1;
        if (!G[i1][j1]) {
          uf.unite(P[n] + 1, x);
        }
      }
    }
    if (!uf.same(P[n] + 1, 0)) {
      ans++;
    }
  }
  cout << ans << endl;
}
