#include <bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimization("Ofast")
#pragma GCC optimization("unroll-loops")
#pragma comment(linker, "/stack:200000000")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
const int MAXN = 505;
const int MAXV = 250005;
const int MOD = 1000000007;
int P[MAXN], N, V;
bool active[MAXV];
vector<pair<int, int> > adjList[MAXV];
int dx[] = {1, -1, N, -N};
int dist[MAXV];
bool visited[MAXV];
int bfs(int S) {
  memset(dist, -1, sizeof dist);
  memset(visited, 0, sizeof visited);
  dist[S] = 0;
  deque<pair<int, int> > dq;
  dq.push_front({S, 0});
  while (!dq.empty()) {
    int node = dq.front().first;
    int curdist = dq.front().second;
    dq.pop_front();
    if (visited[node]) continue;
    visited[node] = 1;
    dist[node] = curdist;
    for (auto e : adjList[node]) {
      int next_n = e.first;
      int edge_w = e.second;
      if (edge_w == 0) {
        dq.push_front({next_n, curdist});
      } else {
        dq.push_back({next_n, curdist + 1});
      }
    }
  }
  int res = 1e9;
  for (int i = (1); i <= (N); i++) res = min(res, dist[i]);
  for (int i = (N * N - N + 1); i <= (V); i++) res = min(res, dist[i]);
  for (int i = 1; i <= V; i += N) res = min(res, dist[i]);
  for (int i = N; i <= V; i += N) res = min(res, dist[i]);
  return res;
}
void gen(int i) {
  vector<int> nx;
  if (i > N) nx.push_back(i - N);
  if (i < N * N - N + 1) nx.push_back(i + N);
  if (i % N != 1) nx.push_back(i - 1);
  if (i % N != 0) nx.push_back(i + 1);
  for (auto j : nx) {
    if (active[j])
      adjList[i].push_back({j, 1});
    else
      adjList[i].push_back({j, 0});
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> N;
  V = N * N;
  for (int i = (1); i <= (V); i++) cin >> P[i];
  for (int i = (1); i <= (V); i++) active[i] = 1;
  for (int i = (1); i <= (V); i++) {
    gen(i);
  }
  int ans = 0;
  for (int i = (1); i <= (V); i++) {
    ans += bfs(P[i]);
    active[P[i]] = 0;
    vector<int> nx;
    if (P[i] > N) nx.push_back(P[i] - N);
    if (P[i] < N * N - N + 1) nx.push_back(P[i] + N);
    if (P[i] % N != 1) nx.push_back(P[i] - 1);
    if (P[i] % N != 0) nx.push_back(P[i] + 1);
    for (auto j : nx) {
      adjList[j].clear();
      gen(j);
    }
    adjList[P[i]].clear();
    gen(P[i]);
  }
  cout << ans;
}
