#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;
 
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define fbo find_by_order
#define ook order_of_key
 
typedef long long ll;
typedef pair<ll,ll> ii;
typedef vector<int> vi;
typedef long double ld; 
typedef tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update> pbds;

struct DSU
{
	int S;
	
	struct node
	{
		int p; ll sum;
	};
	vector<node> dsu;
	
	DSU(int n)
	{
		S = n;
		for(int i = 0; i < n; i++)
		{
			node tmp;
			tmp.p = i; tmp.sum = 0;
			dsu.pb(tmp);
		}
	}
	
	void reset(int n)
	{
		dsu.clear();
		S = n;
		for(int i = 0; i < n; i++)
		{
			node tmp;
			tmp.p = i; tmp.sum = 0;
			dsu.pb(tmp);
		}
	}
	
	int rt(int u)
	{
		if(dsu[u].p == u) return u;
		dsu[u].p = rt(dsu[u].p);
		return dsu[u].p;
	}
	
	void merge(int u, int v)
	{
		u = rt(u); v = rt(v);
		if(u == v) return ;
		if(rand()&1) swap(u, v);
		dsu[v].p = u;
		dsu[u].sum = min(dsu[u].sum,dsu[v].sum);
	}
	
	bool sameset(int u, int v)
	{
		if(rt(u) == rt(v)) return true;
		return false;
	}
	
	ll getstat(int u)
	{
		return dsu[rt(u)].sum;
	}
};

int a[555][555];

const int dx[4]={1,-1,0,0};
const int dy[4]={0,0,1,-1};
int n; 

int getid(int x, int y)
{
	return x*n+y;
}

bool valid(int x, int y)
{
	return (x>=0&&x<n&&y>=0&&y<n);
}

int main()
{
	ios_base::sync_with_stdio(0); cin.tie(0);
	cin>>n;
	ll ans = 0;
	DSU dsu(n*n);
	for(int i=0;i<n*n;i++)
	{
		int x=i/n; int y=i%n;
		dsu.dsu[getid(x,y)].sum=min(x,min(y,min(n-1-x,n-1-y)));
	}
	for(int i=0;i<n*n;i++)
	{
		int v; cin>>v; v--;
		int x=v/n; int y=v%n;
		for(int j=0;j<4;j++)
		{
			int x2=x+dx[j]; int y2=y+dy[j];
			if(valid(x2,y2)&&a[x2][y2])
			{
				dsu.merge(v,getid(x2,y2));
			}
		}
		ans+=dsu.getstat(v);
		a[x][y]=1;
	}
	cout<<ans<<'\n';
}
