#include<bits/stdc++.h>
#define reg register
typedef long long ll;
using namespace std;
const int MN=505;
int n,p[MN*MN],X[MN*MN],Y[MN*MN];
int tim[MN][MN];
typedef pair<int,int>pii;
#define fi first
#define se second
deque<pii>q;
pii stk[MN*MN*2];
int dis[MN][MN],top;
bool vis[MN][MN];
const int dir[2][4]={{1,-1,0,0},{0,0,1,-1}};
int solve(int x){
	for(reg int i=1;i<=n;i++){
		dis[1][i]=dis[i][1]=dis[n][i]=dis[i][n]=0;
		if(!vis[1][i])q.push_back(make_pair(1,i)),vis[1][i]=true,stk[++top]=make_pair(1,i);
		if(!vis[i][1])q.push_back(make_pair(i,1)),vis[i][1]=true,stk[++top]=make_pair(i,1);
		if(!vis[n][i])q.push_back(make_pair(n,i)),vis[n][i]=true,stk[++top]=make_pair(n,i);
		if(!vis[i][n])q.push_back(make_pair(i,n)),vis[i][n]=true,stk[++top]=make_pair(i,n);
	}
	for(reg int i=1;i<=n;i++)
		vis[1][i]=vis[i][1]=vis[n][i]=vis[i][n]=false;
	reg int tx=X[p[x]],ty=Y[p[x]];
	while(!q.empty()){
		reg pii v=q.front();q.pop_front();
		if(vis[v.fi][v.se])continue;
		vis[v.fi][v.se]=true;
		if(make_pair(tx,ty)==v)break;
		for(reg int i=0,dx,dy;i<4;i++){
			dx=v.fi+dir[0][i];dy=v.se+dir[1][i];
			if(dx<1||dy<1||dx>n||dy>n||vis[dx][dy])continue;
			if(dis[dx][dy]>dis[v.fi][v.se]+(tim[v.fi][v.se]>x)){
				dis[dx][dy]=dis[v.fi][v.se]+(tim[v.fi][v.se]>x);
				if(tim[v.fi][v.se]<=x)q.push_front(make_pair(dx,dy));
				else q.push_back(make_pair(dx,dy));
				stk[++top]=make_pair(dx,dy);
			}
		}
	}
	while(!q.empty())q.pop_front();
	reg int res=dis[tx][ty];
	for(reg int i=1;i<=top;i++){
		vis[stk[i].fi][stk[i].se]=false;
		dis[stk[i].fi][stk[i].se]=n+1;
	}
	top=0;
	return res;
}
int main(){
	scanf("%d",&n);
	for(reg int i=1;i<=n*n;i++)
		scanf("%d",p+i),X[i]=(i-1)/n+1,Y[i]=(i-1)%n+1;
	for(reg int i=1;i<=n*n;i++)tim[X[p[i]]][Y[p[i]]]=i;
	for(reg int i=1;i<=n;i++)
		for(reg int j=1;j<=n;j++)
			dis[i][j]=n+1;
	reg ll Ans=0;
	for(reg int i=1;i<=n*n;i++)Ans+=solve(i);
	printf("%lld\n",Ans);
	return 0;
}