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

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

  let
    solve m = do
      forM [1..c] $ \color -> do
        res <- forM [1..n] $ \j -> do
          forM [1..n] $ \i -> do
            if mod (i+j) 3 == m then do
              current <- readArray carr (j,i)
              let next = color
              readArray darr (current, next)
              else
              return 0
        return $ (sum . map sum) res

  m0 <- zip [1..] <$> solve 0
  m1 <- zip [1..] <$> solve 1
  m2 <- zip [1..] <$> solve 2

  print $ minimum [sum [d0,d1,d2] | (i,d0)<-m0, (j,d1)<-m1, (k,d2)<-m2, i/=j, j/=k, i/=k]
  
