#include <bits/stdc++.h>
using namespace std;
inline long long read() {
  long long x = 0;
  char ch = getchar();
  bool f = 0;
  for (; !isdigit(ch); ch = getchar())
    if (ch == '-') f = 1;
  for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0';
  return f ? -x : x;
}
void write(long long x) {
  if (x < 0) putchar('-'), x = -x;
  if (x >= 10) write(x / 10);
  putchar(x % 10 + '0');
}
void writeln(long long x) {
  write(x);
  puts("");
}
void writep(long long x) {
  write(x);
  putchar(' ');
}
const int N = 25, M = (1 << 10) + 5, inf = 1000000;
const int wx[4] = {0, 0, 1, -1}, wy[4] = {1, -1, 0, 0};
int n, m, st, ed, f[N][N][M], sum[M], cnt;
char s[N][N];
struct info {
  int x, y, w;
} a[N];
struct atom {
  int x, y, s;
};
queue<atom> q;
void bfs() {
  memset(f, -1, sizeof(f));
  q.push((atom){st, ed, 0});
  f[st][ed][0] = 0;
  while (q.size()) {
    atom now = q.front();
    q.pop();
    for (int i = (int)(0); i <= (int)(3); i++) {
      int x = now.x + wx[i], y = now.y + wy[i];
      if (x < 1 || x > n || y < 1 || y > m ||
          (s[x][y] != '.' && s[x][y] != 'S'))
        continue;
      int ss = now.s;
      for (int j = (int)(1); j <= (int)(cnt); j++) {
        if (x == a[j].x && y < a[j].y && now.x < x)
          ss ^= (1 << j - 1);
        else if (now.x == a[j].x && now.y < a[j].y && x < now.x)
          ss ^= (1 << j - 1);
      }
      if (f[x][y][ss] == -1) {
        f[x][y][ss] = f[now.x][now.y][now.s] + 1;
        q.push((atom){x, y, ss});
      }
    }
  }
}
int main() {
  n = read();
  m = read();
  for (int i = (int)(1); i <= (int)(n); i++) {
    scanf("%s", s[i] + 1);
    for (int j = (int)(1); j <= (int)(m); j++) {
      if (s[i][j] == 'S') st = i, ed = j;
      if (s[i][j] > '0' && s[i][j] < '9') {
        int p = s[i][j] - '0';
        cnt++;
        a[p].x = i;
        a[p].y = j;
      }
    }
  }
  for (int i = (int)(1); i <= (int)(cnt); i++) a[i].w = read();
  for (int i = (int)(1); i <= (int)(n); i++) {
    for (int j = (int)(1); j <= (int)(m); j++) {
      if (s[i][j] == 'B') a[++cnt] = (info){i, j, -inf};
    }
  }
  for (int ss = (int)(0); ss <= (int)((1 << cnt) - 1); ss++) {
    for (int i = (int)(1); i <= (int)(cnt); i++)
      if (ss & (1 << i - 1)) sum[ss] += a[i].w;
  }
  bfs();
  int ans = 0;
  for (int i = (int)(0); i <= (int)((1 << cnt) - 1); i++)
    if (f[st][ed][i] != -1) {
      ans = max(ans, sum[i] - f[st][ed][i]);
    }
  cout << ans;
}
