#include <bits/stdc++.h>
using namespace std;
int dx[4] = {0, -1, 0, 1};
int dy[4] = {1, 0, -1, 0};
int f[21][21][513], kf[21][21][513], n, m, a[21][21], px[10], py[10], bx[10],
    by[10], bm, trm, sx, sy, v[21][21][513], val[10], ans;
char s[100];
struct node {
  int x, y, s, k;
  node(int x = 0, int y = 0, int s = 0, int k = 0) : x(x), y(y), s(s), k(k){};
};
queue<node> q;
void add(int x, int y, int s, int k, int w) {
  v[x][y][s] = 1;
  f[x][y][s] = w;
  kf[x][y][s] = k;
  q.push(node(x, y, s, k));
}
void bfs(int x, int y) {
  memset(f, -0x3f, sizeof(f));
  add(x, y, 0, 0, 0);
  while (!q.empty()) {
    node now = q.front();
    q.pop();
    for (int i = 0; i < 4; i++) {
      int nx = now.x + dx[i], ny = now.y + dy[i];
      if (a[nx][ny] == 1) {
        int nw = f[now.x][now.y][now.s], ns = now.s, nk = now.k + 1;
        if (abs(dx[i]) == 1) {
          int u = min(now.x, nx);
          for (int j = 1; j <= trm; j++)
            if (px[j] == u && py[j] < ny) {
              ns ^= (1 << (j - 1));
              if (ns & (1 << (j - 1)))
                nw += val[j];
              else
                nw -= val[j];
            }
          for (int j = 1; j <= bm; j++)
            if (bx[j] == u && by[j] < ny) {
              ns ^= 1 << (j + trm - 1);
            }
        }
        if (!v[nx][ny][ns]) add(nx, ny, ns, nk, nw);
      }
    }
  }
  for (int i = 0; i < (1 << (trm)); i++)
    ans = max(ans, f[x][y][i] - kf[x][y][i]);
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) {
    scanf("%s", s);
    for (int j = 0; j < m; j++) {
      if (s[j] == '.')
        a[i][j + 1] = 1;
      else {
        a[i][j + 1] = 2;
        if ('0' <= s[j] && s[j] <= '9')
          trm++, px[s[j] - '0'] = i, py[s[j] - '0'] = j + 1;
        if (s[j] == 'B') bx[++bm] = i, by[bm] = j + 1;
        if (s[j] == 'S') sx = i, sy = j + 1, a[i][j + 1] = 1;
      }
    }
  }
  for (int i = 1; i <= trm; i++) scanf("%d", &val[i]);
  bfs(sx, sy);
  printf("%d", ans);
}
