#include <bits/stdc++.h>
using namespace std;
int n, m;
char s[25][25];
int tnum, bnum;
int tx[10], ty[10], bx[10], by[10];
int f[25][25][260][260];
const int INF = 19950920;
int w[10];
int qx[2000100], qy[2000100], qt[2000100], qb[2000100];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int sx, sy;
int l, r, ans;
int sumw[300];
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; ++i) scanf("%s", s[i] + 1);
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) {
      if (s[i][j] == 'S') sx = i, sy = j;
      if (s[i][j] > '0' && s[i][j] < '9') {
        ++tnum;
        tx[s[i][j] - '0'] = i;
        ty[s[i][j] - '0'] = j;
      }
      if (s[i][j] == 'B') {
        ++bnum;
        bx[bnum] = i;
        by[bnum] = j;
      }
    }
  for (int i = 1; i <= tnum; ++i) scanf("%d", &w[i]);
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      for (int p = 0; p < (1 << tnum); ++p)
        for (int q = 0; q < (1 << bnum); ++q) f[i][j][p][q] = INF;
  l = r = 1;
  qx[1] = sx;
  qy[1] = sy;
  qt[1] = 0;
  qb[1] = 0;
  f[sx][sy][0][0] = 0;
  while (l <= r) {
    int dqx = qx[l], dqy = qy[l], dqt = qt[l], dqb = qb[l];
    l++;
    for (int k = 0; k < 4; ++k) {
      int nx = dqx + dx[k], ny = dqy + dy[k];
      int nt = dqt, nb = dqb;
      if (s[nx][ny] != '.' && s[nx][ny] != 'S') continue;
      for (int i = 1; i <= tnum; ++i) {
        if (ny <= ty[i]) continue;
        if (nx == tx[i] - 1 && dqx == tx[i]) nt ^= (1 << (i - 1));
        if (dqx == tx[i] - 1 && nx == tx[i]) nt ^= (1 << (i - 1));
      }
      for (int i = 1; i <= bnum; ++i) {
        if (ny <= by[i]) continue;
        if (nx == bx[i] - 1 && dqx == bx[i]) nb ^= (1 << (i - 1));
        if (dqx == bx[i] - 1 && nx == bx[i]) nb ^= (1 << (i - 1));
      }
      if (f[nx][ny][nt][nb] > f[dqx][dqy][dqt][dqb] + 1) {
        f[nx][ny][nt][nb] = f[dqx][dqy][dqt][dqb] + 1;
        ++r;
        qx[r] = nx;
        qy[r] = ny;
        qt[r] = nt;
        qb[r] = nb;
      }
    }
  }
  for (int i = 0; i < (1 << tnum); ++i)
    for (int j = 1; j <= tnum; ++j)
      if (i & (1 << (j - 1))) sumw[i] += w[j];
  for (int i = 0; i < (1 << tnum); ++i)
    ans = max(ans, sumw[i] - f[sx][sy][i][0]);
  printf("%d\n", ans);
  return 0;
}
