let () =
  Scanf.scanf "%d %d" @@ fun h w ->

  let c = Array.init 10 (fun _ -> Array.init 10 (fun _ -> Scanf.scanf " %d" ((+) 0))) in
  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;

  Array.init (h*w) (fun _ -> Scanf.scanf " %d" ((+) 0))
  |> Array.fold_left (fun s e ->
      if e = -1 then s else s + c.(e).(1)) 0
  |> Printf.printf "%d\n"