
module Memoizable
  def memoize(name)
    original = "__original_#{name}__"
    self.class.class_eval do
      alias_method original, name
      private original
      define_method(name) do |*args|
        $cache[args] ||= send(original, *args)
      end
    end
  end
end


include Memoizable

def solve(t, pos, bits)
  return 0 if t >= $max_t 
  sum = 0
  for s in $fld[pos]
    if t >= $sales[s][1] && t < $sales[s][2]
      if (bits & (1<<s)) != 0
        sum += $sales[s][0]
        bits ^= (1<<s)
      end
    end
  end
  res = 0
  for p in $mv[pos].each
    tmp = solve(t + 1, p, bits)
    res = [res, tmp].max
  end
  sum + res
end

memoize :solve

def prepare(pos, c)
  y, x = pos.divmod $w
  [[1, 0], [0, -1], [-1, 0], [0, 1]].each do |dx, dy|
    nx, ny = x + dx, y + dy
    if nx >= 0 && nx < $w && ny >= 0 && ny < $h && !$fld[p = ny * $w + nx].nil?
      unless c.nil? 
        $fld[p] += [c] unless $fld[p].include?(c)    
      else $mv[pos] += [p]
      end
    end
  end
end

while true
  $cache = {}
  $w, $h = gets.split(' ').map(&:to_i)
  break if $w == 0
  start = nil
  $fld = ($h*$w).times.map{ [] }

  for y in (0...$h)
    tmp = gets.split(' ')
    for x in (0...$w)
      c = tmp[x]
      start = y * $w + x if c == 'P'
      if ('0'..'9').include? c
        prepare(y * $w + x, c.to_i)
        $fld[y * $w + x] = nil
      end
    end
  end
  $mv = ($h*$w).times.map{ [] }
  for y in (0...$h)
    for x in (0...$w)
      unless $fld[y * $w + x].nil?
        prepare(y * $w + x, nil)
      end
    end
  end
  $n = gets.to_i
  $max_t = 0
  $sales = []
  $n.times do
    arr = gets.split(' ').map(&:to_i)
    $sales[arr[0]] = arr[1..-1]
    $max_t = [$max_t, arr[3]].max
  end
  p solve(0, start, (1 << $n) - 1)
end