#include <bits/stdc++.h>
using namespace std;
int n, m;
char ss[25][25];
int SX, SY;
int pbx[15], pby[15];
int val[15];
int cnt;
int X[15], Y[15];
struct node {
  int s, x, y;
};
int dis[1 << 9][25][25];
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int check(int x, int y) {
  int orz = 0;
  for (int i = 1; i <= cnt; i++) {
    if (X[i] == x && y < Y[i]) orz |= (1 << (i - 1));
  }
  return orz;
}
void ts() { ; }
int main() {
  int fl = 0;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) {
    scanf("%s", &ss[i][1]);
    for (int j = 1; j <= m; j++) {
      if (ss[i][j] == 'S') SX = i, SY = j;
      if (ss[i][j] >= '1' && ss[i][j] <= '8') {
        X[ss[i][j] - '0'] = i;
        Y[ss[i][j] - '0'] = j;
        cnt = max(cnt, ss[i][j] - '0');
      }
      if (ss[i][j] == 'B') {
        pbx[++fl] = i;
        pby[fl] = j;
      }
    }
  }
  for (int i = 1; i <= cnt; i++) {
    scanf("%d", &val[i]);
  }
  for (int i = 1; i <= fl; i++) {
    X[++cnt] = pbx[i];
    Y[cnt] = pby[i];
  }
  queue<node> q;
  memset(dis, -1, sizeof dis);
  dis[0][SX][SY] = 0;
  q.push((node){0, SX, SY});
  ss[SX][SY] = '.';
  while (q.size()) {
    int x = q.front().x;
    int y = q.front().y;
    int so = q.front().s;
    q.pop();
    for (int i = 0; i < 4; i++) {
      int nx = x + dx[i];
      int ny = y + dy[i];
      if (ss[nx][ny] != '.') continue;
      int nts = so;
      if (i == 1) {
        nts ^= check(x, y);
      }
      if (i == 0) {
        nts ^= check(nx, ny);
      }
      if (dis[nts][nx][ny] != -1) continue;
      q.push((node){nts, nx, ny});
      dis[nts][nx][ny] = dis[so][x][y] + 1;
    }
  }
  int ans = 0;
  int bj;
  bj = (1 << (cnt - fl)) - 1;
  for (int s = 1; s <= bj; s++) {
    if (dis[s][SX][SY] == -1) continue;
    int sm = 0;
    for (int i = 1; i <= cnt - fl; i++) {
      sm += ((s >> (i - 1)) & 1) * val[i];
    }
    ans = max(ans, sm - dis[s][SX][SY]);
  }
  printf("%d", ans);
  return 0;
  printf("%23333");
}
