program main
   implicit none
   integer::N,C
   integer,allocatable,dimension(:,:)::D
   integer,allocatable,dimension(:,:)::Cs
   integer,allocatable,dimension(:,:)::T
   integer::i,j,k,m
   integer::ans,preans
   read*,N,C
   allocate(D(C,C))
   do i=1,C
      read*,D(i,:)
   end do
   allocate(Cs(N,N))
   do i=1,N
      read*,Cs(i,:)
   end do

   allocate(T(0:2,C))
   T=0
   do i=1,N
      do j=1,N
         T(mod(i+j,3),Cs(i,j))=T(mod(i+j,3),Cs(i,j))+1
      end do
   end do
   
   ans=huge(ans)
   do i=1,C
      do j=1,C
         do k=1,C
            if((i-j)*(j-k)*(k-i)==0)cycle
            preans=0
            do m=1,C
               preans=preans+D(m,i)*T(0,m)+D(m,j)*T(1,m)+D(m,k)*T(2,m)
            end do
            ans=min(ans,preans)
         end do
      end do
   end do
   print"(I0)",ANS
contains

end program main