import Data.Array.IO
import Data.Array.Unboxed
import Data.List
import Control.Monad
import Control.Applicative

modifyArray arr i f = readArray arr i >>= \x -> writeArray arr i (f x)

main = do
  (n:c:_) <- getLine >>= return . map read . words :: IO [Int]
  darr <- newArray ((1,1),(c,c)) 0 :: IO (IOUArray (Int, Int) Int)

  forM_ [1..c] $ \i -> do
    temp <- getLine >>= return . map read . words :: IO [Int]
    forM_ (zip [1..c] temp) $ \(j, d) -> do
      writeArray darr (i,j) d

  countArray <- newArray ((0,1),(2,c)) 0 :: IO (IOUArray (Int,Int) Int)
  
  forM_ [1..n] $ \i -> do
    temp <- getLine >>= return . map read . words :: IO [Int]
    forM_ (zip [1..n] temp) $ \(j, c) -> do
      modifyArray countArray (mod (i+j) 3, c) (+1)

  s <- forM [[i,j,k]| i<-[1..c], j<-[1..c], k<-[1..c], i/=j, j/=k, i/=k] $ \colors -> do
    c <- forM [0..2] $ \m -> do
      forM [1..c] $ \x -> do
        count <- readArray countArray (m,x)
        d <- readArray darr (x,colors!!m)
        return $ d * count
    return $ (sum . map sum) c

  print $ minimum s
