#include <iostream>
#include <queue>
using namespace std;

int dy[] = {-1,0,1,0};
int dx[] = {0,1,0,-1};

class Item{
public:
	int n,c,s,g;
	Item(int n=0,int c=0,int s=0,int g=0):n(n),c(c),s(s),g(g){}
};

class State{
public:
	int x,y,cost,sum,visited;
	State(int x=0,int y=0,int c=0,int s=0,int v=0):x(x),y(y),cost(c),sum(s),visited(v){}
};

int main(){
	int h,w;
	while(cin >> w >> h && h && w){
		int a[20][20], n, ans = 0;
        bool G[20][20];
        int n_i[10]; //商品番号を配列の番号に変換
		bool f[20][20][(1<<8)];
		Item item[8];
		queue<State> Q;
		State u,v;
		for(int i=0;i<h;i++){
			for(int j=0;j<w;j++){
				for(int k=0;k<(1<<8);k++) f[i][j][k] = false;

				char c;
				cin >> c;
				G[i][j] = true;
				a[i][j] = -1;
				if(c == '.') G[i][j] = false;
				else if(c == 'P'){
					u.y = i;
					u.x = j;
					f[i][j][0] = true;
					G[i][j] = false;
				} else a[i][j] = c - '0';
			}
		}

		cin >> n;
		for(int i=0;i<n;i++){
			cin >> item[i].n >> item[i].c >> item[i].s >> item[i].g;
            n_i[item[i].n] = i;
		}

		Q.push(u);
		while(!Q.empty()){
			u = Q.front();
			Q.pop();
            
			for(int i=0;i<4;i++){
				v = u;
				v.y += dy[i];
				v.x += dx[i];
				v.cost++;
				if(v.y >= 0 && v.y < h && v.x >= 0 && v.x < w && !f[v.y][v.x][v.visited]){
                    if(!G[v.y][v.x]){
                        f[v.y][v.x][v.visited] = true;
                        Q.push(v);
                    }
                    else if((v.visited & (1<<n_i[a[v.y][v.x]])) == 0){
                        if(u.cost >= item[n_i[a[v.y][v.x]]].s && u.cost < item[n_i[a[v.y][v.x]]].g){
                            State v2 = u;
                            //f[v2.y][v2.x][v2.visited] = true;
                            v2.visited = v2.visited | (1<<n_i[a[v.y][v.x]]);
                            f[v2.y][v2.x][v2.visited] = true;
                            v2.sum += item[n_i[a[v.y][v.x]]].c;
                            ans = max(ans,v2.sum);
                            if(v2.visited != ((1<<n)-1)) Q.push(v2);
                        } else if(u.cost < item[n_i[a[v.y][v.x]]].s){
                            //変更点
                            State v2 = u;
                            v2.cost += item[n_i[a[v.y][v.x]]].s - v2.cost;
                            Q.push(v2);
                            //ここまで
                        }
                    }
                }
            }
            
        }
        cout << ans << endl;
    }
}