import qualified Data.ByteString.Char8         as B
import qualified Data.Vector.Unboxed           as U
import           Data.List
import           Control.Monad

main = do
  [n, c] <- map read . words <$> getLine
  d      <- U.concat <$> replicateM c readIntsU
  a      <- U.concat <$> replicateM n readIntsU
  print $f n c d a
f :: Int -> Int -> U.Vector Int -> U.Vector Int -> Int
f n c d a = minimum
  [ f cs | cs <- replicateM 3 [0 .. c - 1], length (nub cs) == 3 ] where
  f cs = sum $zipWith g cs cns
  g y = sum . zipWith f [0 .. c - 1] where f x cn = d U.! (x * c + y) * cn
  cns = map f [0 .. 2]   where
    f m =
      map (pred . length)
        $  group
        $  sort
        $  [1 .. c]
        ++ [ a U.! (i * n + j)
           | i <- [0 .. n - 1]
           , j <- [0 .. n - 1]
           , mod (i + j) 3 == m
           ]
readIntsU = U.unfoldr (B.readInt . B.dropWhile (== ' ')) <$> B.getLine
