#include <bits/stdc++.h>
using namespace std;
struct Package {
  int x, y, bt, bs;
  Package() {}
  Package(int _x, int _y, int _bt, int _bs) : x(_x), y(_y), bt(_bt), bs(_bs) {}
};
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
char grid[25][25];
int v[10], sx, sy, n, m;
int bx[10], by[10], cb, tx[10], ty[10], ct;
int f[25][25][1 << 8][1 << 8];
bool inq[25][25][1 << 8][1 << 8];
queue<Package> q;
int spfa() {
  memset(f, 0xc0, sizeof(f));
  f[sx][sy][0][0] = 0;
  inq[sx][sy][0][0] = 1;
  q.push(Package(sx, sy, 0, 0));
  while (!q.empty()) {
    Package t = q.front();
    q.pop();
    inq[t.x][t.y][t.bt][t.bs] = 0;
    for (int i = 0; i < 4; i++) {
      int xx = t.x + dx[i], yy = t.y + dy[i];
      if (xx <= 0 || xx > n || yy <= 0 || yy > m || grid[xx][yy] != '.')
        continue;
      int tt = t.bt, tb = t.bs, tf = f[t.x][t.y][t.bt][t.bs] - 1;
      for (int j = 1; j <= cb; j++)
        if (((yy < by[j] && t.y == by[j]) || (yy == by[j] && t.y < by[j])) &&
            bx[j] > xx)
          tb ^= 1 << j - 1;
      for (int j = 1; j <= ct; j++)
        if (((yy < ty[j] && t.y == ty[j]) || (yy == ty[j] && t.y < ty[j])) &&
            tx[j] > xx)
          tt ^= 1 << j - 1, tf += ((tt & (1 << j - 1)) ? v[j] : -v[j]);
      if (tf > f[xx][yy][tt][tb]) {
        f[xx][yy][tt][tb] = tf;
        if (!inq[xx][yy][tt][tb])
          q.push(Package(xx, yy, tt, tb)), inq[xx][yy][tt][tb] = 1;
      }
    }
  }
  int ans = 0;
  for (int i = 0; i < (1 << ct); i++) ans = max(ans, f[sx][sy][i][0]);
  return ans;
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) {
    scanf("%s", grid[i] + 1);
    for (int j = 1; j <= m; j++) {
      if (grid[i][j] == 'S')
        sx = i, sy = j, grid[i][j] = '.';
      else if (grid[i][j] == 'B')
        cb++, bx[cb] = i, by[cb] = j;
      else if (grid[i][j] != '.' && grid[i][j] != '#') {
        int p = grid[i][j] - '0';
        ct = max(ct, p), tx[p] = i, ty[p] = j;
      }
    }
  }
  for (int i = 1; i <= ct; i++) scanf("%d", &v[i]);
  printf("%d\n", spfa());
  return 0;
}
