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

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

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

  s <- forM (concat [permutations [i,j,k] | i<-[1..c], j<-[i+1..c], k<-[j+1..c]]) $ \color -> do
    res <- forM [1..n] $ \j -> do
      forM [1..n] $ \i -> do
        current <- readArray carr (j,i)
        let next = color!!(mod (i+j) 3)
        readArray darr (current, next)
    return $ (sum . map sum) res
  
  print $ minimum s
  
