#include<bits/stdc++.h>
using namespace std;
int n,m,dp[25002],a[25002],ans,b[25002];
#define re register
inline int read(){
	re int t=0;re char v=getchar();
	while(v<'0')v=getchar();
	while(v>='0')t=(t<<3)+(t<<1)+v-48,v=getchar();
	return t;
}
inline int pos(re int x,re int y){
	return (x-1)*n+y;
}
inline void dfs(re int x,re int y){if(b[x])--y;
	if(y>=dp[x])return;
	dp[x]=y;
	if(x>n)dfs(x-n,y+1);
	if(x<=n*n-n)dfs(x+n,y+1);
	if(x%n>1)dfs(x-1,y+1);
	if(x%n)dfs(x+1,y+1);
}
int main(){
	n=read();
	for(re int i=1;i<=n*n;++i)a[i]=read();
	for(re int i=1;i<=n;++i)for(re int j=1;j<=n;++j)dp[(i-1)*n+j]=min(i-1,min(j-1,min(n-i,n-j)));
	for(re int i=1;i<=n*n;++i){
		ans+=dp[a[i]];b[a[i]]=1;
		dfs(a[i],dp[a[i]]);
	}
	printf("%d",ans);
}