#include <bits/stdc++.h>
using namespace std;
int dat[501][501] = {};
int dir[501][501] = {};
int dat2[501][501] = {};
bool block[501][501] = {};
struct S {
  int x;
  int y;
  int v;
};
auto cmp = [](const S& lhs, const S& rhs) { return lhs.v > rhs.v; };
void enqueue(int x, int y, int v, int n, int m,
             priority_queue<S, vector<S>, decltype(cmp)>& s) {
  if (x == -1 || x == n || y == -1 || y == n) return;
  if (dat2[x][y] == m) return;
  if (dat[x][y] <= v) return;
  s.push({x, y, v});
}
bool evaluate(int x, int y, int v, int d, int n) {
  if (x <= 0 || n - 1 <= x || y <= 0 || n - 1 <= y) return false;
  if (dir[x][y] != d) return false;
  if (x != 0) {
    int c = 0;
    if (block[x - 1][y]) c++;
    if (dat[x - 1][y] + c < v) {
      dat[x][y] = dat[x - 1][y];
      dir[x][y] = 0;
      return false;
    }
  }
  if (x != n - 1) {
    int c = 0;
    if (block[x + 1][y]) c++;
    if (dat[x + 1][y] + c < v) {
      dat[x][y] = dat[x + 1][y];
      dir[x][y] = 1;
      return false;
    }
  }
  if (y != 0) {
    int c = 0;
    if (block[x][y - 1]) c++;
    if (dat[x][y - 1] + c < v) {
      dat[x][y] = dat[x][y - 1];
      dir[x][y] = 2;
      return false;
    }
  }
  if (y != n - 1) {
    int c = 0;
    if (block[x][y + 1]) c++;
    if (dat[x][y + 1] + c < v) {
      dat[x][y] = dat[x][y + 1];
      dir[x][y] = 3;
      return false;
    }
  }
  dat[x][y] = v;
  return true;
}
void update(int x, int y, int v, int n, int m) {
  priority_queue<S, vector<S>, decltype(cmp)> search(cmp);
  search.push({x, y, v});
  while (!search.empty()) {
    S s = search.top();
    search.pop();
    if (dat2[s.x][s.y] == m) continue;
    dat2[s.x][s.y] = m;
    int cv = s.v;
    if (block[s.x][s.y]) cv++;
    if (evaluate(s.x - 1, s.y, cv, 1, n)) {
      search.push({s.x - 1, s.y, cv});
    }
    if (evaluate(s.x + 1, s.y, cv, 0, n)) {
      search.push({s.x + 1, s.y, cv});
    }
    if (evaluate(s.x, s.y - 1, cv, 3, n)) {
      search.push({s.x, s.y - 1, cv});
    }
    if (evaluate(s.x, s.y + 1, cv, 2, n)) {
      search.push({s.x, s.y - 1, cv});
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout << fixed << setprecision(20);
  int n;
  cin >> n;
  int64_t ans = 0;
  vector<int> cs(n * n);
  for (auto& c : cs) cin >> c;
  for (auto it = cs.rbegin(); it != cs.crend(); it++) {
    int m = *it;
    m--;
    int x = m % n;
    int y = m / n;
    int v = dat[x][y];
    block[x][y] = true;
    update(x, y, v, n, m + 1);
    ans += v;
  }
  cout << ans << endl;
  return 0;
}
