#include <bits/stdc++.h>
using namespace std;
const int fx[4] = {0, 0, -1, 1}, fy[4] = {1, -1, 0, 0};
int n, m, sx, sy, S, Sb;
pair<int, int> p[11], bb[11], tt[11];
int ntt, nbb;
int f[22][22][1 << 10];
int a[22][22], value[11];
char s1[22];
struct HF {
  int x, y, sta;
  HF(int _x, int _y, int _sta) {
    x = _x;
    y = _y;
    sta = _sta;
  }
  HF() {}
};
queue<HF> q;
HF pre[22][22][1 << 10];
int cha(int x, int y, int xx, int yy) { return x * yy - y * xx; }
int calc(int ax, int ay, int bx, int by, int &res) {
  for (int i = 1, j = 1; i <= ntt + nbb; ++i, j <<= 1) {
    if (ay < p[i].second && (ax == p[i].first && bx > p[i].first ||
                             ax > p[i].first && bx == p[i].first))
      res ^= j;
  }
}
void solve() {
  memset(f, -1, sizeof f);
  f[sx][sy][0] = 0;
  q.push(HF(sx, sy, 0));
  for (; !q.empty(); q.pop()) {
    HF v = q.front();
    for (int k = 0; k < 4; ++k) {
      int nx = v.x + fx[k], ny = v.y + fy[k];
      if (!a[nx][ny]) continue;
      int ns = v.sta;
      calc(v.x, v.y, nx, ny, ns);
      HF pp = pre[v.x][v.y][v.sta];
      if (nx == pp.x && ny == pp.y) continue;
      if (!~f[nx][ny][ns]) {
        f[nx][ny][ns] = f[v.x][v.y][v.sta] + 1;
        pre[nx][ny][ns] = HF(v.x, v.y, v.sta);
        q.push(HF(nx, ny, ns));
      }
    }
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; ++i) {
    scanf("%s", s1 + 1);
    for (int j = 1; j <= m; ++j) {
      if (s1[j] == '.' || s1[j] == 'S') {
        a[i][j] = 1;
        if (s1[j] == 'S') sx = i, sy = j;
      } else {
        a[i][j] = 0;
        if (s1[j] == 'B')
          bb[++nbb] = make_pair(i, j);
        else if (s1[j] != '#') {
          ntt = max(ntt, s1[j] - '0');
          tt[s1[j] - '0'] = make_pair(i, j);
        }
      }
    }
  }
  S = 1 << ntt + nbb;
  S--;
  Sb = (1 << ntt) - 1;
  for (int i = 1; i <= ntt; ++i) {
    p[i] = tt[i];
    scanf("%d", &value[i]);
  }
  for (int i = ntt + 1; i <= ntt + nbb; ++i) p[i] = bb[i - ntt];
  solve();
  int ans = 0;
  for (int sta = 0; sta < (1 << ntt); ++sta) {
    int ls = 0;
    for (int i = 0; i < ntt; ++i)
      if ((sta >> i) & 1) ls += value[i + 1];
    if (f[sx][sy][sta] >= 0) {
      ans = max(ans, ls - f[sx][sy][sta]);
    }
  }
  printf("%d\n", ans);
}
