program test
implicit none
integer :: i,j,k,m,n,c
integer :: d(30,30),color(500,500),color_num(0:2,500)=0,iwakan(0:2,500)=0,iwa_total,temp

read(*,*) n,c
do i=1,c
	read(*,*) (d(i,j),j=1,c)
enddo

do i=1,n
	read(*,*) (color(i,j),j=1,n)
enddo

do i=1,n
	do j=1,n
		color_num(mod(i+j,3),color(i,j)) = color_num(mod(i+j,3),color(i,j)) + 1
	enddo
enddo

do j=1,c !塗り替える後の色
	do i=1,c	!塗り替える前の色
		do k=0,2
			iwakan(k,j) = iwakan(k,j) + d(i,j) * color_num(k,i)
		enddo
	enddo
enddo

iwa_total = 10 ** 9

do i=1,c
	do j=1,c
		do k=1,c
			if(i.ne.j .and. i.ne.k .and. j.ne.k) then
				temp = iwakan(0,i) + iwakan(1,j) + iwakan(2,k)
				iwa_total = min(iwa_total,temp)
			endif
		enddo
	enddo
enddo

write(*,*) iwa_total

end program