let h, w = Scanf.scanf " %d %d" @@ fun a b -> a, b
let css = Array.init 10 @@ fun _ -> Array.init 10 @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let a_ss = Array.init h @@ fun _ -> Array.init w @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let dp = Array.make_matrix 10 10 0
let ms = Array.make 10 0
let ans = ref 0
let _ =
  for i = 0 to 9 do dp.(i).(1) <- css.(i).(1) done;
  for i = 2 to 9 do
    for j = 0 to 9 do
      let m = ref max_int in
      for k = 0 to 9 do if j <> k then m := min !m @@ css.(j).(k) + dp.(k).(i - 1) done;
      dp.(j).(i) <- !m done done;
  for i = 0 to 9 do
    if i <> 1 then
      let m = ref max_int in
      for j = 1 to 9 do m := min !m @@ dp.(i).(j) done;
      ms.(i) <- !m done;
  for i = 0 to h - 1 do
    for j = 0 to w - 1 do
      if a_ss.(i).(j) <> -1 then ans := !ans + ms.(a_ss.(i).(j)) done done;
  Printf.printf "%d\n" !ans