#include #define rep(i,n) for (int i=0; i<(int)(n); i++) #define REP(i,m,n) for(ll i=(ll)(m);i<(ll)(n);i++) using namespace std; using ll = long long; using P = pair; int main() { int n; cin >> n; int INFTY = 100100100; vector> A(n, vector(n)); rep(i,n) rep(j,n) { int a; cin >> a; A[i][j] = --a; } vector dx = {-1, 0, 1, -1, 1, -1, 0, 1}; vector dy = {-1, -1, -1, 0, 0, 1, 1, 1}; map sp; int ans = 0; rep(i, n) sp[i] = INFTY; int d = INFTY; rep(i,n) { queue

q; vector> dist(n, vector(n, INFTY)); q.push(make_pair(i,0)); int cnt = 0; map d; dist[i][0] = 0; while (cnt != n*n){ cnt++; P p = q.front(); q.pop(); int x = p.first; int y = p.second; d[A[x][y]] += dist[x][y]; rep(j, 8) { int nx = x + dx[j]; int ny = y + dy[j]; if (0 <= nx && nx < n && 0 <= ny && ny < n) { if (dist[nx][ny] == INFTY) { q.push(make_pair(nx,ny)); dist[nx][ny] = dist[x][y] + 1; } } } } for (auto m : d) { sp[m.first] = min(sp[m.first], m.second); } } for (auto s: sp) { ans += s.second; } cout << ans << endl; }