Scanf.scanf "%d %d" (fun h w ->
    let c = Array.init 10 (fun _ ->
        Array.init 10 (fun _ -> Scanf.scanf " %d" (fun c -> c)))
    in
    let d = Array.make 10 0 in
    for i = 1 to h do
        for j = 1 to w do
            Scanf.scanf " %d" (fun a ->
                if a >= 0 then d.(a) <- d.(a) + 1
            )
        done
    done;
    for k = 0 to 9 do
        for i = 0 to 9 do
            for j = 0 to 9 do
                c.(i).(j) <- min c.(i).(j) (c.(i).(k) + c.(k).(j))
            done
        done
    done;
    let rec loop i acc =
        if i = 10 then acc else loop (i + 1) (acc + d.(i) * c.(i).(1))
    in
    loop 0 0 |> Printf.printf "%d\n"
)