import Control.Arrow
import Data.List
import qualified Data.ByteString.Char8 as B
import Control.Monad 
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import Control.Monad.ST

main :: IO ()
main = breads >>= main'
    where
        main' [n, c] = replicateM c breads >>= main'' c n . build
        main'' c n ds = replicateM n breads >>= print . solve c n ds . build . map (map pred)

type V2 a = V.Vector (V.Vector a)

at :: V2 a -> (Int, Int) -> a
at vs (x, y) = vs V.! x V.! y
    
build :: [[Int]] -> V2 Int
build = V.fromList . map V.fromList

solve :: Int -> Int -> V2 Int -> V2 Int -> Int
solve c n ds cs = minimum [calc x y z | x <- [0..(c - 1)], y <- [0..(c - 1)], z <- [0..(c - 1)], x /= y, y /= z, z /= x]
    where
        [cs0, cs1, cs2] = map count [0..2]

        calc x y z = sum [diff x cs0, diff y cs1, diff z cs2]
        diff v xs = foldl' (\acc x -> acc + xs V.! x * ds `at` (x, v)) 0 [0..(c - 1)]
        count :: Int -> V.Vector Int 
        count m = runST $ newVec >>= loop >>= V.unsafeFreeze
            where
                newVec :: ST s (VM.STVector s Int) 
                newVec = VM.replicate c 0
                loop vs = vs <$ mapM_ mf [(i, j) | i <- [0..(n - 1)], j <- [0..(n - 1)], (i + j + 2) `mod` 3 == m]
                    where
                        mf idx = VM.unsafeModify vs succ $ cs `at` idx

breads :: IO [Int]
breads = unfoldr (\s -> second (maybe B.empty snd . B.uncons) <$> B.readInt s) <$> B.getLine