program main
    implicit none
	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(0: 2, 1:C))
	
	
	S(0:2, 1: C) = 0
	do i = 1, C
		do j = 1, N, 3
			if(j/3 == 1) then
				do k = 2, N, 3
					S(0, i) = S(0, i) + D(cl(j,k), i)
				end do
			else if(j/3 == 2) then
				do k = 1, N, 3
					S(0, i) = S(0, i) + D(cl(j,k), i)
				end do
			else 
				do k = 2, N, 3
					S(0, i) = S(0, i) + D(cl(j,k), i)
				end do
			end if
		end do
	end do
	

	do i = 1, C
		do j = 1, N, 3
			if(j/3 == 1) then
				do k = 3, N, 3
					S(1, i) = S(1, i) + D(cl(j,k), i)
				end do
			else if(j/3 == 2) then
				do k = 2, N, 3
					S(1, i) = S(1, i) + D(cl(j,k), i)
				end do
			else 
				do k = 1, N, 3
					S(1, i) = S(1, i) + D(cl(j,k), i)
				end do
			end if
		end do
	end do
	
	
	do i = 1, C
		do j = 1, N, 3
			if(j/3 == 1) then
				do k = 1, N, 3
					S(2, i) = S(2, i) + D(cl(j,k), i)
				end do
			else if(j/3 == 2) then
				do k = 3, N, 3
					S(2, i) = S(2, i) + D(cl(j,k), i)
				end do
			else 
				do k = 2, N, 3
					S(2, i) = S(2, i) + D(cl(j,k), i)
				end do
			end if
		end do
	end do
	
	ans = 9000000
	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(0,i) + S(1,j) + S(2, k), ans)
				end if
			end do
		end do
	end do
	
	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(1,i) + S(2,j) + S(0, k), ans)
				end if
			end do
		end do
	end do
	
	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(2,i) + S(0,j) + S(1, k), ans)
				end if
			end do
		end do
	end do
	write(*, *) ans
end program main