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

memoize :solve

def prepare(x, y, c)
  [[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[ny][nx].nil?
      unless c.nil? 
        $fld[ny][nx] += [c] unless $fld[ny][nx].include?(c)    
      else $mv[y][x] += [[nx, ny]]
      end
    end
  end
end

while true
  $cache = {}

  $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
        prepare(x, y, c.to_i)
        $fld[y][x] = nil
      end
    end
  end
  $mv = $h.times.map{ Array.new($w, []) }
  for y in (0...$h)
    for x in (0...$w)
      unless $fld[y][x].nil?
        prepare(x, y, 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, sx, sy, (1 << $n) - 1)
end