#include <bits/stdc++.h>
using namespace std;
char s[30][30];
int n, m;
int val[20], go[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int dis[21][21][256][256];
int v[30][30], vb[30][30];
struct _ {
  int x, y, st, sb;
};
queue<_> q;
void bfs(int sx, int sy) {
  q.push({sx, sy, 0, 0});
  dis[sx][sy][0][0] = 0;
  _ t;
  int i;
  int tx, ty, tt, tb, d;
  while (!q.empty()) {
    t = q.front();
    d = dis[t.x][t.y][t.st][t.sb];
    q.pop();
    for (i = 0; i < 4; i++) {
      tx = t.x;
      ty = t.y;
      tt = t.st;
      tb = t.sb;
      tx += go[i][0];
      ty += go[i][1];
      if (tx <= 0 || ty <= 0) continue;
      if (tx > n || ty > m) continue;
      if (s[tx][ty] != '.' && s[tx][ty] != 'S') continue;
      if (i < 2) {
        int xx, j;
        xx = t.y;
        if (i == 1) xx--;
        for (j = tx; j <= n; j++) {
          if (v[j][xx]) tt ^= 1 << v[j][xx] - 1;
        }
        for (j = tx; j <= n; j++) {
          if (vb[j][xx]) tb ^= 1 << vb[j][xx] - 1;
        }
      }
      if (dis[tx][ty][tt][tb] < 10000000) continue;
      dis[tx][ty][tt][tb] = d + 1;
      q.push({tx, ty, tt, tb});
    }
  }
}
int vv(int st) {
  int i, rv = 0;
  for (i = 0; i < 8; i++) {
    if (st & 1 << i) {
      rv += val[i + 1];
    }
  }
  return rv;
}
int main() {
  memset(dis, 31, sizeof(dis));
  scanf("%d%d", &n, &m);
  int i;
  for (i = 1; i <= n; i++) {
    scanf("%s", s[i] + 1);
  }
  int j;
  int t = 0, cnt = 0;
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= m; j++) {
      if ('1' <= s[i][j] && s[i][j] <= '9') t++, v[i][j] = s[i][j] - '0';
      if (s[i][j] == 'B') s[i][j] = ++cnt, vb[i][j] = s[i][j];
    }
  }
  for (i = 1; i <= t; i++) {
    scanf("%d", &val[i]);
  }
  int sx, sy;
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= m; j++) {
      if (s[i][j] == 'S') {
        sx = i;
        sy = j;
      }
    }
  }
  bfs(sx, sy);
  int ans = 0;
  for (i = 0; i < 1 << t; i++) {
    ans = max(ans, vv(i) - dis[sx][sy][i][0]);
  }
  printf("%d\n", ans);
  return 0;
}
