{-# LANGUAGE FlexibleContexts, RankNTypes #-}
import Control.Arrow
import Control.Monad
import Control.Monad.ST
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Vector as V 
import qualified Data.Vector.Mutable as MV

main :: IO ()
main = readLine >>= main'
    where
        main' xs = inputs xs >>= print . uncurry solve 
        inputs [h, w] = (,) <$> readContents 10 <*> readContents h

solve :: [[Int]] -> [[Int]] -> Int
solve cs = sum . map (sum . map count) 
    where
        count a 
            | a < 0 = 0 
            | otherwise = value a

        value a = vs V.! (10 * a + 1)

        vs = V.create $ do 
            vs <- MV.new 100 :: ST s (MV.STVector s Int)
            mapM_ (uncurry (MV.unsafeWrite vs)) . zip [0..] $ concat cs 

            forM_ [(i, j, k) | i <- [0..9], j <- [0..9], k <- [0..9]] $  \(i, j, k) -> do 
                a <- MV.unsafeRead vs $ i * 10 + j 
                b <- MV.unsafeRead vs $ i * 10 + k
                c <- MV.unsafeRead vs $ k * 10 + j
                MV.unsafeWrite vs (i * 10 + j) . min a $ b + c

            return vs


readLine :: IO [Int]
readLine = unfoldr (fmap (second (maybe B.empty snd . B.uncons)) . B.readInt) <$> B.getLine

readContents :: Int -> IO [[Int]]
readContents = flip replicateM readLine