### constant

INF = 1 << 30

DXYS = [[1, 0], [0, 1], [-1, 0], [0, -1]]

C_STRAIGHT = 0
C_RIGHT = 1
C_BACK = 2
C_LEFT = 3
C_HALT = 4

### main

loop do
  w, h = gets.split.map(&:to_i)
  break if (w | h) == 0

  brds = h.times.map{gets.split.map(&:to_i)}
  costs = gets.split.map(&:to_i)
  #p brds
  #p costs

  dists = h.times.map{w.times.map{4.times.map{INF}}}
  dists[0][0][0] = 0
  q = [[0, 0, 0]]

  min_cost = INF
  gx = w - 1
  gy = h - 1

  while ! q.empty?
    u = q.min{|a, b| dists[a[1]][a[0]][a[2]] <=> dists[b[1]][b[0]][b[2]]}
    q.delete(u)

    ux, uy, ud = u
    distu = dists[uy][ux][ud]
    brdu = brds[uy][ux]

    if ux == gx && uy == gy
      min_cost = distu if min_cost > distu
      next
    end

    for cmd in (0..3)
      vd = (ud + cmd) & 3
      dx, dy = DXYS[vd]
      vx = ux + dx
      vy = uy + dy

      if vx >= 0 && vx < w && vy >= 0 && vy < h
        cost = (brdu == cmd) ? 0 : costs[cmd]
        distv = dists[vy][vx][vd]
        ndistv = distu + cost

        if distv > ndistv
          q << [vx, vy, vd] if distv >= INF
          dists[vy][vx][vd] = ndistv
        end
      end
    end
  end

  puts min_cost
end