#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#include <math.h>
#include <string>
#include <cstring>
#include <set>
#include <map>
#include <unordered_map>

using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef pair<int,pair<int,int>> piii;
typedef vector<int> vi;
typedef vector<pii> vii;

#define ri(a) scanf("%d", &a)
#define rii(a,b) scanf("%d %d", &a, &b)
#define riii(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define rl(a) scanf("%lld", &a)
#define rll(a,b) scanf("%lld %lld", &a, &b)
#define FOR(i,n,m) for(int i=n; i<m; i++)
#define ROF(i,n,m) for(int i=n; i>m; i--)
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define F first
#define S second

const int INF = 0x3f3f3f3f;
const ll LLINF = 1e18;
const int maxN = 505; // CAMBIAR ESTE

// GJNM
int n;
int mat[maxN][maxN];
int A[maxN*maxN];
ll dp[maxN*maxN][4];

ll f(int ind, int choice){ 
	if ( ind == n*n )
		return 0;
	if ( dp[ind][choice] != -1 )
		return dp[ind][choice];

	ll &ret = dp[ind][choice];
	ret = LLINF;
	
	int row = get_row(A[ind]), col = get_col(A[ind]);
	ll aux = 0;
	if ( choice == 0 ){ // go up
		mat[row][col] = 0;
		FOR(i,0,row)
			aux += mat[i][col];
	
		FOR(i,0,4)
			ret = min(ret, aux + f(ind+1, i) );
		
		mat[row][col] = 1;
	}
	else if ( choice == 1 ){ // go down	
		mat[row][col] = 0;
		FOR(i,row+1,n)
			aux += mat[i][col];
	
		FOR(i,0,4)
			ret = min(ret, aux + f(ind+1, i) );
		
		mat[row][col] = 1;	
	}
	else if ( choice == 2 ){ // go left
		mat[row][col] = 0;

		FOR(i,0,col)
			aux += mat[row][i];
	
		FOR(i,0,4)
			ret = min(ret, aux + f(ind+1, i) );
		
		mat[row][col] = 1;
	}
	else{ // go right
		mat[row][col] = 0;

		FOR(i,col,n)
			aux += mat[row][i];
	
		FOR(i,0,4)
			ret = min(ret, aux + f(ind+1, i) );
		
		mat[row][col] = 1;
	}
	return ret;
}

int main(){
	ri(n);
	FOR(i,0,n){
		FOR(j,0,n){
			mat[i][j] = 1;
		}
	}
	
	FOR(i,0,n*n){
		ri(A[i]);
		A[i]--;
	}

	FOR(i,0,maxN){
		dp[i][0] = dp[i][1] = dp[i][2] = dp[i][3] = -1;
	}

	printf("%lld\n", min( min( f(0,0), f(0,1) ), min( f(0,2), f(0,3) ) ) );
	return 0;
}