N = int(input()) A = [list(map(int, input().split())) for _ in range(N)] acc = [[0]*(N+1) for _ in range(N)] cost = [0]*N for i in range(N): for j in range(N): id = A[i][j]-1 cost[id] += max(i,j) if i==0: if j+1<=N: acc[id][j+1] += 1 acc[id][-1] -= 1 elif j==0: acc[id][1] -= 1 acc[id][i+1] += 1 acc[id][i+1] += 1 acc[id][-1] -= 1 elif i==j: if i*2+1<=N: acc[id][i*2+1] += 1 acc[id][-1] -= 1 elif i>j: acc[id][1] -= 1 acc[id][i-j+1] += 1 if i+j+1<=N: acc[id][i+j+1] += 1 acc[id][-1] -= 1 else: if i+j+1<=N: acc[id][i+j+1] += 1 acc[id][-1] -= 1 res = 0 for i in range(N): for j in range(N): acc[i][j+1] += acc[i][j] for j in range(N): acc[i][j+1] += acc[i][j] res += cost[i]+min(acc[i][:-1]) print(res)