#include <bits/stdc++.h>
using namespace std;
const int maxn = 23;
const int inf = 0x3f3f3f3f;
int n, m, cnt, stx, sty, MSK[maxn][maxn], d[maxn][maxn][1 << 9],
    dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1}, cost[maxn], id[maxn][maxn];
bool emp[maxn][maxn];
int solve(int x, int y) {
  memset(d, 0x3f, sizeof(d));
  d[x][y][0] = 0;
  queue<int> q;
  q.push(x);
  q.push(y);
  q.push(0);
  int msk;
  while (!q.empty()) {
    x = q.front();
    q.pop();
    y = q.front();
    q.pop();
    msk = q.front();
    q.pop();
    for (int dir = 0; dir < 4; ++dir) {
      int tx = x + dx[dir], ty = y + dy[dir];
      if (tx < 0 || tx > n || ty < 0 || ty > m || !emp[tx][ty]) continue;
      int tmsk = msk;
      if (dir == 0) tmsk ^= MSK[x][y];
      if (dir == 1) tmsk ^= MSK[tx][ty];
      if (d[tx][ty][tmsk] == inf) {
        d[tx][ty][tmsk] = d[x][y][msk] + 1;
        q.push(tx);
        q.push(ty);
        q.push(tmsk);
      }
    }
  }
  int res = 0;
  for (int i = 0; i < (1 << cnt); ++i) {
    if (d[stx][sty][i] == inf) continue;
    int ans = -d[stx][sty][i];
    for (int j = 1; j <= cnt; ++j)
      if (i & (1 << j - 1)) ans += cost[j];
    res = max(res, ans);
  }
  return res;
}
char s[maxn][maxn];
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; ++i) {
    scanf("%s", s[i] + 1);
    for (int j = 1; j <= m; ++j)
      if (isdigit(s[i][j])) {
        id[i][j] = s[i][j] - '0';
        ++cnt;
      }
  }
  for (int i = 1; i <= cnt; ++i) scanf("%d", &cost[i]);
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      if (s[i][j] == 'B') cost[id[i][j] = ++cnt] = -1e7;
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j) {
      emp[i][j] = (s[i][j] == '.' || s[i][j] == 'S');
      if (s[i][j] == 'S') stx = i, sty = j;
    }
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      if (id[i][j])
        for (int k = j + 1; k <= m; ++k) MSK[i - 1][k] |= (1 << id[i][j] - 1);
  printf("%d\n", solve(stx, sty));
  return 0;
}
