#include using namespace std; struct fast_ios { fast_ios(){ cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_; #define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i=i##_begin_;i--) #define REP(i, n) FOR(i,0,n) #define IREP(i, n) IFOR(i,0,n) template bool chmin(T &m, const T q) { if (m > q) {m = q; return true;} else return false; } template istream &operator>>(istream &is, vector &vec){ for (auto &v : vec) is >> v; return is; } int main() { int N; cin >> N; vector A(N, vector(N)); cin >> A; vector i1(N, vector(N)), i2(N, vector(N)); int ret = 0; REP(i, N) REP(j, N) { int k = A[i][j] - 1; ret += j; if (i + j + 1 < N) i1[k][i + j + 1]++; if (i - j - 1 >= 0) i2[k][i - j - 1]++; } REP(_, 2) REP(i, N) REP(j, N - 1) i1[i][j + 1] += i1[i][j]; REP(_, 2) REP(i, N) IREP(j, N - 1) i2[i][j] += i2[i][j + 1]; REP(i, N) { int tmp = 1e9; REP(j, N) chmin(tmp, i1[i][j] + i2[i][j]); ret += tmp; } cout << ret << '\n'; }