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

D = [[1, 0], [0, -1], [-1, 0], [0, 1]]
include Memoizable

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

memoize :solve

while true
  $w, $h = gets.split(' ').map(&:to_i)
  break if $w == 0
  start = nil
  $fld = $h.times.map{ Array.new($w, []) }
    
  for y in (0...$h)
    tmp = gets.split(' ')
    for x in (0...$w)
      c = tmp[x]
      sx, sy = x, y if c == 'P'
      if ('0'..'9').include? c
        c = c.to_i
        D.each do |dx, dy|
          nx, ny = x + dx, y + dy
          if nx >= 0 && nx < $w && ny >= 0 && ny < $h && !$fld[ny][nx].nil?
            $fld[ny][nx] += [c]
          end
        end
        $fld[y][x] = nil
      end
    end
  end
  p $fld
  $fld.each{|arr| arr.map{|a| a.uniq! unless a.nil?}}
  $mv = $h.times.map{ Array.new($w, []) }
  for y in (0...$h)
    for x in (0...$w)
      unless $fld[y][x].nil?
        D.each do |dx, dy|
          nx, ny = x + dx, y + dy
          if nx >= 0 && nx < $w && ny >= 0 && ny < $h && !$fld[ny][nx].nil?
            $mv[ny][nx] += [[x, y]]
          end
        end
      end
    end
  end
  p $fld
  p $mv
  $n = gets.to_i
  $max_t = 0

  $sales = $n.times.each_with_object([]){ |_, arr| tmp = gets.split(" ").map(&:to_i); arr << tmp[0]; arr << tmp[1,3]; $max_t = [$max_t, tmp[3]].max }
  $sales = Hash[*$sales]
 
  p solve(0, sx, sy, (1 << $n) - 1)
end