program main
	integer N, C, i, j, k
	integer(8) ans
	integer, allocatable :: D(:, :), cl(:, :), S(:, :)
	read(*, *) N, C
	allocate(D(1: C, 1:C))
	do i = 1, C
		read(*, *) D(i, 1: C)
	end do
	allocate(cl(1: N, 1:N))
	do i = 1, N
		read(*, *) cl(i, 1:N)
	end do
	allocate(S(1:C, 0:2))
	S(1:C, 0:2) = 0
	do l = 0, 2
		do k = 1, C
			do j = 1, N
				do i = 1, N
					if(mod(i+j, 3) == l) then
						S(k, l) = S(k, l) + D(cl(i,j), k)
					end if
				end do
			end do
		end do
	end do
	ans = 300000000
	do i = 1, C
		do j = 1, C
			do k = 1, C
				if(i /= j .and. j /= k .and. k /= i) then
					ans = min(S(i,0) + S(j,1) + S(k, 2), ans)
				end if
			end do
		end do
	end do
	write(*, *) ans
end program main