import Control.Monad
import Control.Applicative
import Data.Functor
import Data.List
import Data.List.Split
import Data.Char
import Data.Ord
import Data.Array.IO
import Data.IORef

readInt = read :: String -> Int
getInt = readLn :: IO Int
getInts = map readInt . words <$> getLine
sjoin :: (Show a) => [a] -> String
sjoin = unwords . map show
cond :: a -> a -> Bool -> a
cond t f c = if c then t else f
-- end of templete

wf arr range = do
    forM_ range $ \k -> do
        forM_ range $ \i -> do
            forM_ range $ \j -> do
                before <- readArray arr (i,j)
                after1 <- readArray arr (i,k)
                after2 <- readArray arr (k,j)
                writeArray arr (i,j) $ min before $ after1 + after2

cost arr (-1) = return 0
cost arr n = readArray arr (n,1)

main = do
    arr <- newArray ((0,0),(9,9)) 1234 :: IO (IOUArray (Int, Int) Int)
    [h, w] <- getInts
    forM_ [0..9] $ \i -> do
        cs <- getInts
        forM_ (zip cs [0..9]) $ \(c, j) -> writeArray arr (i,j) c
    wf arr [0..9]
    ref <- newIORef 0
    walls <- concat <$> replicateM h getInts
    forM_ walls $ \n -> do
        cost arr n >>= modifyIORef ref . (+)
    readIORef ref >>= print
    return ()

