(* quite naive implementation *)
let rec dikjstra ( +. ) ( < ) q edge d =
  match q with
  | [] -> ()
  | u :: q ->
      let u, q = 
        List.fold_left (fun (u, q') u' ->
          if d.(u) < d.(u') then (u, u' :: q')
          else (u', u :: q')) (u, []) q in
      List.iter (fun (v, c) ->
        if c +. d.(u) < d.(v) then
          d.(v) <- c +. d.(u)) (edge u);
      dikjstra ( +. ) ( < ) q edge d

let () =
  let h, w = Scanf.scanf "%d %d\n" (fun h w -> h, w) in
  let css =
    Array.init 10 (fun _ ->
      Array.init 10 (fun i ->
        Scanf.scanf "%d " (fun c -> c))) in
  let css' =
    Array.init 10 (fun i ->
      Array.to_list @@ Array.init 10 (fun j -> (j, css.(j).(i)))) in
  let ass =
    Array.init h (fun _ ->
      Array.init w (fun _ ->
        Scanf.scanf "%d " (fun a -> a))) in
  let cost = Array.make 10 1145141919 in
  cost.(1) <- 0;
  dikjstra ( + ) ( < ) [1; 2; 3; 4; 5; 6; 7; 8; 9; 0] (fun i -> css'.(i)) cost;
  Printf.printf "%d\n" @@ Array.fold_left ( + ) 0 @@ Array.map (fun as_ ->
    Array.fold_left ( + ) 0 @@ Array.map (function -1 -> 0 | n -> cost.(n)) as_) ass
