#include <bits/stdc++.h>
using namespace std;
inline int read() {
  bool f = 0;
  int s = 0;
  char c;
  while ((c = getchar()) < '0' || c > '9')
    if (c == '-') f = 1;
  do {
    s = s * 10 + c - '0';
  } while ((c = getchar()) >= '0' && c <= '9');
  return f ? -s : s;
}
const int N = 30, mask = (1 << 8) - 1;
const int dir[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
int n, m, si, sj, t, trt, ti[N], tj[N], v[N];
int dist[N][N][1 << 8];
bool inq[N << 16];
char g[N][N];
queue<int> q;
int sol() {
  int i, j;
  memset(dist, 0x7f, sizeof dist);
  dist[si][sj][0] = 0;
  q.push((((si) << 16) + ((sj) << 8) + (0)));
  inq[(((si) << 16) + ((sj) << 8) + (0))] = 1;
  while (!q.empty()) {
    int hn = q.front();
    q.pop();
    int ii = (hn >> 16), jj = (hn >> 8) & mask, kk = hn & mask;
    int hs = dist[ii][jj][kk];
    int tgi, tgj, tgk, tg;
    for (int dd = 0; dd < 4; dd++)
      if (g[tgi = ii + dir[dd][0]][tgj = jj + dir[dd][1]] == '.') {
        tgk = kk;
        if (dd == 0)
          for (int tt = 0; tt < t; tt++)
            if (ti[tt] > ii && tj[tt] == jj) tgk ^= 1 << tt;
        if (dd == 1)
          for (int tt = 0; tt < t; tt++)
            if (ti[tt] > ii && tj[tt] == tgj) tgk ^= 1 << tt;
        if (hs + 1 < dist[tgi][tgj][tgk]) {
          dist[tgi][tgj][tgk] = hs + 1;
          tg = (((tgi) << 16) + ((tgj) << 8) + (tgk));
          if (!inq[tg]) inq[tg] = 1, q.push(tg);
        }
      }
    inq[hn] = 0;
  }
  int tmp, ans = 0;
  for (i = 0; i < (1 << trt); i++) {
    tmp = 0;
    for (j = 0; j < trt; j++)
      if (i & (1 << j)) tmp += v[j];
    tmp -= dist[si][sj][i];
    if (tmp > ans) ans = tmp;
  }
  return ans;
}
int main() {
  int i, j;
  n = read();
  m = read();
  for (i = 1; i <= n; i++) {
    scanf("%s", &g[i][1]);
    for (j = 1; j <= m; j++)
      if (g[i][j] >= '1' && g[i][j] <= '8')
        ti[g[i][j] - '1'] = i, tj[g[i][j] - '1'] = j, t++;
      else if (g[i][j] == 'S')
        si = i, sj = j, g[i][j] = '.';
  }
  trt = t;
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++)
      if (g[i][j] == 'B') ti[t] = i, tj[t] = j, t++;
  for (i = 0; i < trt; i++) v[i] = read();
  printf("%d\n", sol());
  return 0;
}
