#include #include #include #include #define rep(i, start, end) for (int i = (int)start; i < (int)end; ++i) #define rrep(i, start, end) for (int i = (int)start - 1; i >= (int)end; --i) #define all(x) (x).begin(), (x).end() using namespace std; using ll = long long; template inline bool chmax(T& a, T b) {if (a < b) {a = b; return true;} return 0;} template inline bool chmin(T& a, T b) {if (a > b) {a = b; return true;} return 0;} int main() { cin.tie(0); ios::sync_with_stdio(false); int N; cin >> N; vector> A(N, vector(N)); rep(i, 0, N) rep(j, 0, N) { cin >> A[i][j]; --A[i][j]; } using P = pair; vector> pos(N); rep(i, 0, N) rep(j, 0, N) { pos[A[i][j]].emplace_back(i, j); } vector ans(N, 1 << 30); rep(i, 0, N) { int h = i, w = 0; rep(j, 0, N) { int now_ans = 0; for (auto p : pos[j]) { now_ans += abs(h - p.first) + abs(w - p.second) - min(abs(h - p.first), abs(w - p.second)); } chmin(ans[j], now_ans); } } cout << accumulate(all(ans), 0) << endl; return 0; }