#include <bits/stdc++.h>
using namespace std;
int R, C;
char g[22][22];
int m[22][22], v[10], b, q, t;
int si, sj;
pair<int, pair<int, int> > fila[2000000];
int cost[22][22][300];
int di[] = {-1, 0, 1, 0};
int dj[] = {0, 1, 0, -1};
bool pode(int i, int j) {
  return i >= 0 && i < R && j >= 0 && j < C && g[i][j] == '.';
}
void bfs() {
  fila[0] = make_pair(0, make_pair(si, sj));
  memset(cost, -1, sizeof(cost));
  cost[si][sj][0] = 0;
  for (int st = 0, fn = 0; st <= fn; st++) {
    int xi = fila[st].second.first;
    int xj = fila[st].second.second;
    int xm = fila[st].first;
    for (int k = 0; k < 4; k++) {
      int ni = xi + di[k];
      int nj = xj + dj[k];
      if (pode(ni, nj)) {
        int nm = xm;
        if (k == 0)
          nm ^= m[ni][nj];
        else if (k == 2)
          nm ^= m[xi][xj];
        if (cost[ni][nj][nm] == -1) {
          cost[ni][nj][nm] = cost[xi][xj][xm] + 1;
          fila[++fn] = make_pair(nm, make_pair(ni, nj));
        }
      }
    }
  }
}
int main() {
  memset(m, 0, sizeof(m));
  memset(v, 0, sizeof(v));
  b = q = t = 0;
  scanf("%d%d", &R, &C);
  for (int i = 0; i < R; i++) {
    scanf("%s", g[i]);
    for (int j = 0; j < C; j++) {
      if (g[i][j] != '.') {
        if (g[i][j] == 'S') {
          si = i, sj = j;
          g[i][j] = '.';
        } else if (g[i][j] != '#') {
          if (g[i][j] == 'B')
            b |= (1 << q);
          else if (g[i][j] >= '1' && g[i][j] <= '9')
            v[q] = g[i][j] - '1' + 1000, t++;
          if (i > 0)
            for (int k = j; k >= 0; k--) m[i - 1][k] |= (1 << q);
          q++;
          g[i][j] = '#';
        }
      }
    }
  }
  for (int i = 0; i < t; i++) {
    int val;
    scanf("%d", &val);
    for (int j = 0; j < q; j++)
      if (v[j] == i + 1000) v[j] = val;
  }
  bfs();
  int LIM = (1 << q);
  int res = 0;
  for (int i = 0; i < LIM; i++) {
    if (!(i & b)) {
      int val = 0;
      for (int j = 0; j < q; j++)
        if ((i >> j) & 1) val += v[j];
      if (~cost[si][sj][i]) res = max(res, val - cost[si][sj][i]);
    }
  }
  printf("%d\n", res);
}
