#include using namespace std; using ll = long long; using P = pair; using Graph = vector>; #define rep(i, n) for(ll i=0;i<(ll)(n);i++) #define rep2(i, m, n) for(ll i=m;i<(ll)(n);i++) #define rrep(i, n, m) for(ll i=n;i>=(ll)(m);i--) const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; const int ddx[8] = {0, 1, 1, 1, 0, -1, -1, -1}; const int ddy[8] = {1, 1, 0, -1, -1, -1, 0, 1}; const ll MOD = 1000000007; const ll INF = 1000000000000000000L; #ifdef __DEBUG /** * For DEBUG * https://github.com/ta7uw/cpp-pyprint */ #include "cpp-pyprint/pyprint.h" #endif void Main() { ll N; cin >> N; vector> grid(N, vector(N)); vector cnt(N, 0); vector> point(N); rep(i, N) { rep(j, N) { ll a; cin >> a; grid[i][j] = a; cnt[a - 1] += i + 1; point[a - 1].emplace_back(i + 1, j + 1); } } ll ans = 0; rep(t, N) { ll h = cnt[t]; h /= N; ll M = INF; rep2(h2, h - 100, h + 100) { ll ans2 = 0; rep(j, N) { P p = point[t][j]; if (p.first == h2) { ans2 += p.second - 1; } else if (p.second == 1) { ans2 += abs(p.first - h2); } else { ll f = abs(1 - p.second); ll s = abs(p.first - h2); ll m = min(f, s); ll add = m + abs(f - m) + abs(s - m); ans2 += add; } } M = min(M, ans2); } ans += M; } cout << ans << '\n'; } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); Main(); return 0; }