/*** author: yuji9511 ***/ #include using namespace std; using ll = long long; using lpair = pair; const ll MOD = 1e9+7; const ll INF = 1e18; #define rep(i,m,n) for(ll i=(m);i<(n);i++) #define rrep(i,m,n) for(ll i=(m);i>=(n);i--) #define printa(x,n) for(ll i=0;i void print(H&& h, T&&... t){cout<(t)...);} int main(){ cin.tie(0); ios::sync_with_stdio(false); ll N; cin >> N; ll A[1010][1010]; rep(i,0,N){ rep(j,0,N){ cin >> A[i][j]; A[i][j]--; } } vector pos[1010]; rep(i,0,N){ rep(j,0,N){ pos[A[i][j]].push_back({i,j}); } } ll ans = 0; rep(i,0,N){ ll lb = 0, ub = N+1; while(ub - lb > 2){ ll t1 = (2 * lb + ub) / 3; ll t2 = (2 * ub + lb) / 3; ll res1 = 0, res2 = 0; for(auto &e: pos[i]){ ll diff_x = abs(t1 - e.first); res1 += min(diff_x, e.second) + abs(diff_x - e.second); diff_x = abs(t2 - e.first); res2 += min(diff_x, e.second) + abs(diff_x - e.second); } if(res1 <= res2){ ub = t2; }else{ lb = t1; } } ll min_val = INF; for(ll p = max(0LL, lb-1); p < min(N-1, ub+1); p++){ ll res = 0; for(auto &e: pos[i]){ ll diff_x = abs(p - e.first); res += min(diff_x, e.second) + abs(diff_x - e.second); } min_val = min(min_val, res); } ans += min_val; } print(ans); }