#include <bits/stdc++.h>
#define Int int64_t

using namespace std;

int main() {
	int N;
	cin >> N;
	int n = N * N;
	vector<int> P(n);
	for (int i = 0; i < n; ++i) {
		cin >> P[i];
		--P[i];
	}

	vector<int> cost(n, 0);
	for (int i = 0; i < n; ++i) {
		int x = i % N, y = i / N;
		cost[i] = min({ x, N - 1 - x, y, N - 1 - y });
	}

	int dx[4] = { 0, 0, 1, -1 };
	int dy[4] = { 1, -1, 0, 0 };
	auto in = [&](int x, int y) -> bool {
		return x >= 0 && x < N && y >= 0 && y < N;
	};
	int ans = 0;
	vector<bool> rest(n, true);
	for (int i = 0; i < n; ++i) {
		ans += cost[P[i]];
		rest[P[i]] = false;

		deque<int> que;
		que.emplace_back(P[i]);
		while (!que.empty()) {
			int v = que.back(); que.pop_back();
			int x = v % N, y = v / N;
			for (int k = 0; k < 4; ++k) {
				int nx = x + dx[k];
				int ny = y + dy[k];
				int nv = ny * N + nx;
				if (!in(nx, ny) || cost[nv] <= cost[v] + rest[v]) {
					continue;
				}
				cost[nv] = cost[v] + rest[v];
				que.emplace_back(nv);
			}
		}
	}
	cout << ans << endl;

	return 0;
}
