#include #define rep(i,n) for(int i = 0; i < (n); ++i) #define srep(i,s,t) for (int i = s; i < t; ++i) #define drep(i,n) for(int i = (n)-1; i >= 0; --i) using namespace std; typedef long long int ll; typedef pair P; #define yn {puts("YES");}else{puts("NO");} #define MAX_N 200005 int main() { int n; cin >> n; int a[n][n]; rep(i,n)rep(j,n){scanf("%d", &a[i][j]); a[i][j]--;} int ans = 0; priority_queue, greater> l[n]; priority_queue r[n]; rep(i,n){ rep(j,n){ ans += j; l[a[i][j]].push(i+j+1); r[a[i][j]].push(i-j-1); } } int sum[n][n]; rep(i,n)rep(j,n)sum[i][j] = 0; rep(i,n){ int now = 0; rep(j,n){ while(l[i].size() && l[i].top() <= j){ now++; l[i].pop(); } sum[i][j] += now; } now = 0; drep(j,n){ while(r[i].size() && r[i].top() >= j){ now++; r[i].pop(); } sum[i][j] += now; } int mi = 1001001001; rep(j,n)mi = min(mi, sum[i][j]); ans += mi; } cout << ans << endl; return 0; }