#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
const long long INF_LL = (long long)1000000007 * 1000000007;
const int INF_INT = (int)1000000007;
const double PI = 3.14159265358979323846;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
struct IoSetup {
  IoSetup() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(20);
  }
} iosetup;
template <class T>
inline bool chmin(T &a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
template <class T>
inline bool chmax(T &a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
int sheet[600][600];
int seen[600][600];
struct pos {
  int x, y, cost;
  pos(int _x, int _y, int _cost) {
    x = _x;
    y = _y;
    cost = _cost;
  }
};
signed main() {
  int N;
  cin >> N;
  int count = 0;
  vector<int> posX;
  vector<int> posY;
  for (int i = (0); i < (N); ++i) {
    for (int j = (0); j < (N); ++j) {
      count++;
      int p;
      cin >> p;
      p--;
      int h = p / N;
      int w = p % N;
      sheet[w][h] = count;
      posX.emplace_back(w);
      posY.emplace_back(h);
    }
  }
  int ans = 0;
  for (int i = (0); i < (N * N); ++i) {
    queue<pos> que;
    vector<vector<int>> hateCount(N, vector<int>(N, INF_INT));
    que.push(pos(posX[i], posY[i], 0));
    int minCost = INF_INT;
    while (!que.empty()) {
      auto now = que.front();
      que.pop();
      int x = now.x;
      int y = now.y;
      int cost = now.cost;
      if (cost >= minCost) continue;
      for (int j = (0); j < (4); ++j) {
        int hate = 0;
        int nextX = x + dx[j];
        int nextY = y + dy[j];
        if (nextX >= N || nextX < 0 || nextY >= N || nextY < 0) {
          chmin(minCost, cost);
          continue;
        }
        int nextCost = cost;
        if (hateCount[nextX][nextY] <= nextCost) continue;
        if (sheet[nextX][nextY] >= i) {
          nextCost++;
        }
        hateCount[nextX][nextY] = nextCost;
        que.push(pos(nextX, nextY, nextCost));
      }
    }
    ans += minCost;
  }
  cout << ans << endl;
}
