import Control.Monad
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as BS
main=do
 [h,w]<-map read.words<$>getLine
 c<-replicateM 10 (map (read.BS.unpack).BS.words<$>BS.getLine)
 a<-replicateM h (map (read.BS.unpack).BS.words<$>BS.getLine)
 print(f (foldr (++) [] a) (g (k (zip [0..9] c)) [10000,0,10000,10000,10000,10000,10000,10000,10000,10000] (S.insert 1 S.empty)))
  where k [] = []
        k ((i,a):c) = (map (\(n,j)->(n,i,j)) (zip a [0..9]))++(k c)
        g c l s | (S.size s)==10 = l
                | otherwise = (\(_,i,_)->g c ((take i l)++[minimum(p c l i)]++(drop (i+1) l)) (S.insert i s)) (minimum (m c s))
        m [] s = []
        m ((a,i,j):c) s = if (not(S.member i s))&&(S.member j s) then ((a,i,j):(m c s)) else (m c s)
        p c l i = map (\n->((\(n,i,j)->n)(c!!(10*i+n)))+(l!!n)) [0..9]
        f [] l = 0
        f (n:a) l = (l!!(abs n))+(f a l)