from collections import deque
def hate(x,y):
    cur_hate = 0
    cur_q = set()
    next_q = set()
    cur_q.add((x,y))
    already = set()
    while True:
        while cur_q:
            x,y = cur_q.pop()
            for i in range(4):
                next_x = x+dx[i]
                next_y = y+dy[i]
                if not (next_x,next_y) in already:
                    if grid[next_y][next_x] == "o":
                        if cur_hate == 0:
                            for x,y in already:
                                grid[y][x] = "o"
                        return cur_hate
                    if grid[next_y][next_x] == "#":
                        next_q.add((next_x,next_y))
                    else:
                        cur_q.add((next_x,next_y))
                    already.add((x,y))
        cur_hate += 1
        cur_q = next_q
        next_q = set()
n = int(input())
grid = []
grid.append(["o"]*(n+2))
for i in range(n):
    grid.append(["o"]+["#"]*n+["o"])
grid.append(["o"]*(n+2))
dx = [0,1,0,-1]
dy = [1,0,-1,0]
ans = 0
p = list(map(int,input().split()))
for i in range(n**2):
    pos = p[i]
    x = (pos-1)%n+1
    y = (pos-1)//n+1
    h = hate(x,y)
    ans += h
    if h == 0:
        grid[y][x] = "o"
    else:
        grid[y][x] = "."
print(ans)
