#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define ll long long
#define rep(i,l,r)for(ll i=(l);i<(r);i++)
#define repp(i,l,r,k)for(ll i=(l);i<(r);i+=(k))
#define INF ((1LL<<62)-(1LL<<31))
#define max(p,q)((p)>(q)?(p):(q))
#define min(p,q)((p)<(q)?(p):(q))
#define bit(n,m)(((n)>>(m))&1)
int upll(const void*a, const void*b){return*(ll*)a<*(ll*)b?-1:*(ll*)a>*(ll*)b?1:0;}
int downll(const void*a, const void*b){return*(ll*)a<*(ll*)b?1:*(ll*)a>*(ll*)b?-1:0;}
void sortup(ll*a,int n){qsort(a,n,sizeof(ll),upll);}
void sortdown(ll*a,int n){qsort(a,n,sizeof(ll),downll);}
ll pom(ll a,ll n,int m){ll x=1;for(a%=m;n;n/=2)n&1?x=x*a%m:0,a=a*a%m;return x;}
//#define MOD 998244353
#define MOD 1000000007
#define invp(a,p)pom(a,p-2,p)

//union-find
#define UFLIMIT (1<<18)
int unicnt[UFLIMIT+10];//正ならcnt、非正なら根のindex
void ufinit(int n){rep(i,0,n)unicnt[i]=1;}
int ufroot(int x){return unicnt[x]<=0?-(unicnt[x]=-ufroot(-unicnt[x])):x;}
int ufsame(int x,int y){return ufroot(x)==ufroot(y);}
void uni(int x,int y){if((x=ufroot(x))==(y=ufroot(y)))return;if(unicnt[x]<unicnt[y]){int t=x;x=y;y=t;}unicnt[x]+=unicnt[y];unicnt[y]=-x;}
#undef UFLIMIT


int a[500*500+10];
int ans[500*500+10];
int flag[510][510];

void uniuni(int p,int q){
	int temp=min(ans[ufroot(p)],ans[ufroot(q)]);
	uni(p,q);
	ans[ufroot(p)]=temp;
}

int main(){
	int n;
	scanf("%d",&n);
	rep(i,0,n*n)scanf("%d",a+i),a[i]--;
	rep(i,0,n)rep(j,0,n)ans[i*n+j]=min(min(i,n-1-i),min(j,n-1-j));
	
	ufinit(n*n);
	ll aaaaa=0;
	rep(i,0,n*n){
		int x=a[i]/n;
		int y=a[i]%n;
		if(x!=  0&&flag[x-1][y])uniuni(a[i],a[i]-n);
		if(x!=n-1&&flag[x+1][y])uniuni(a[i],a[i]+n);
		if(y!=  0&&flag[x][y-1])uniuni(a[i],a[i]-1);
		if(y!=n-1&&flag[x][y+1])uniuni(a[i],a[i]+1);
		flag[x][y]=1;
		aaaaa+=ans[ufroot(a[i])];
	}
	printf("%lld",aaaaa);
}