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 :: Int -> IO [Int]
    solve m = do
        forM [1..c] $ \color -> do
          res <- forM [(j,i) | j<-[1..n], i<-[1..n], mod (i+j) 3 == m] $ \(j,i) -> do
            current <- readArray carr (j,i)
            readArray darr (current, color)
          return $ 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]
