#include <bits/stdc++.h>
using namespace std;
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
int n, m, nt, nb;
struct Point {
  int x, y;
  Point(int _x = 0, int _y = 0) { x = _x, y = _y; }
  inline bool in() { return x > 0 && x <= n && y > 0 && y <= m; }
} S, t[10], b[10];
struct Node {
  int x, y, ts, bs;
  Node(int _x = 0, int _y = 0, int _ts = 0, int _bs = 0) {
    x = _x, y = _y, ts = _ts, bs = _bs;
  }
  void out() { printf("%d %d %d %d\n", x, y, ts, bs); }
} q[200010];
char a[25][25];
int p[25];
int d[25][25][4], e[25][25][4];
int f[21][21][256][256];
inline void bfs() {
  memset(f, -1, sizeof f);
  int l = 1, r = 1, ts, bs;
  f[S.x][S.y][0][0] = 0;
  q[1] = Node(S.x, S.y, 0, 0);
  Node tp;
  Point T;
  while (l <= r) {
    tp = q[l++];
    for (int i = 0; i < 4; ++i) {
      T = Point(tp.x + dx[i], tp.y + dy[i]);
      if (!T.in() || a[T.x][T.y] != '.') continue;
      ts = tp.ts ^ d[tp.x][tp.y][i];
      bs = tp.bs ^ e[tp.x][tp.y][i];
      if (f[T.x][T.y][ts][bs] != -1) continue;
      f[T.x][T.y][ts][bs] = f[tp.x][tp.y][tp.ts][tp.bs] + 1;
      q[++r] = Node(T.x, T.y, ts, bs);
    }
  }
}
int v[10];
int main() {
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= n; ++i) {
    scanf("%s", a[i] + 1);
    for (int j = 1; j <= m; ++j) {
      if (a[i][j] == 'S') {
        S = Point(i, j);
        a[i][j] = '.';
      }
      if (a[i][j] > '0' && a[i][j] < '9') {
        t[a[i][j] - '0'] = Point(i, j);
        nt = max(nt, a[i][j] - '0');
      }
      if (a[i][j] == 'B') b[++nb] = Point(i, j);
    }
  }
  for (int i = 0; i <= 20; ++i) p[i] = 1 << i;
  for (int i = 1; i <= nt; ++i)
    if (t[i].y < m)
      for (int j = 1; j < t[i].x; ++j) {
        d[j][t[i].y][0] |= p[i - 1];
        d[j][t[i].y + 1][2] |= p[i - 1];
      }
  for (int i = 1; i <= nb; ++i)
    if (b[i].y < m)
      for (int j = 1; j < b[i].x; ++j) {
        e[j][b[i].y][0] |= p[i - 1];
        e[j][b[i].y + 1][2] |= p[i - 1];
      }
  bfs();
  for (int i = 1; i <= nt; ++i) scanf("%d", v + i);
  int ans = 0;
  for (int i = 0; i < p[nt]; ++i) {
    if (f[S.x][S.y][i][0] == -1) continue;
    int value = 0;
    for (int j = 1; j <= nt; ++j)
      if (i & (1 << (j - 1))) value += v[j];
    if (value - f[S.x][S.y][i][0] > ans) ans = value - f[S.x][S.y][i][0];
  }
  printf("%d\n", ans);
  return 0;
}
