program joker
  implicit none
  integer :: n, p(250000) = 0, h(0:501, 0:501) = 0, i, j, k
  integer :: di(4) = (/0, 1, 0, -1/), dj(4) = (/1, 0, -1, 0/)
  logical :: u(0:501, 0:501) = .false.
  integer(8) :: m = 0
  read(*,*) n
  read(*,*) p(1:n * n)
  do i = 1, n
    do j = 1, n
      h(i, j) = min(i - 1, n - i, j - 1, n - j)
      u(i, j) = .true.
    end do
  end do
  do k = 1, n * n
    i = (p(k) - 1) / n + 1
    j = mod(p(k) - 1, n) + 1
    m = m + h(i, j)
    u(i, j) = .false.
    call dfs(i, j)
  end do
  write(*,'(i0)') m
contains
  recursive subroutine dfs(i, j)
    integer, intent(in) :: i, j
    integer :: k, x, y, d
    d = h(i, j) + merge(1, 0, u(i, j))
    do k = 1, 4
      x = i + di(k)
      y = j + dj(k)
      if (h(x, y) > d) then
        h(x, y) = d
        call dfs(x, y)
      end if
    end do
  end
end program joker