local mmi = math.min
local h, w = io.read("*n", "*n")
local map = {}
for i = 1, 100 do map[i] = io.read("*n") end

local tasks = {2}
local tasknum, done = 1, 0
local cost = {}
for i = 1, 10 do cost[i] = 10000 end
cost[2] = 0
while(done < tasknum) do
  done = done + 1
  local dst = tasks[done]
  for i = 1, 10 do
    if(i ~= 2 and i ~= dst) then
      local v = cost[dst] + map[dst + (i - 1) * 10]
      if v < cost[i] then
        cost[i] = v
        tasknum = tasknum + 1
        table.insert(tasks, i)
      end
    end
  end
end

local tot = 0
for i = 1, h * w do
  local a = io.read("*n")
  if 0 <= a then
    tot = tot + cost[a + 1]
  end
end
print(tot)
