#include <bits/stdc++.h>
using namespace std;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};
int read() {
  char c;
  int x = 0, f = 1;
  while (!isdigit(c = getchar())) f -= 2 * (c == '-');
  while (isdigit(c)) {
    x = x * 10 + f * (c - 48);
    c = getchar();
  }
  return x;
}
struct state {
  int x, y, s;
  state(int a = 0, int b = 0, int c = 0) {
    x = a;
    y = b;
    s = c;
  }
};
struct point {
  int x, y;
  point(int a = 0, int b = 0) {
    x = a;
    y = b;
  }
};
point p[11];
char c[22][22];
int n, m, s, t, cnt;
int v[11], sum[256], f[22][22][256];
int chk(int x, int y, int xx, int yy, int i) {
  if (y == p[i].y && x > p[i].x && y < yy) return 1;
  if (yy == p[i].y && xx > p[i].x && yy < y) return 1;
  return 0;
}
int judge(int x, int y) {
  if (!x) return 0;
  if (!y) return 0;
  if (x > n) return 0;
  if (y > m) return 0;
  return 1;
}
void tomax(int& x, int y) {
  if (x < y) x = y;
}
int dp() {
  queue<state> q;
  q.push(state(s, t, 0));
  memset(f, -1, sizeof(f));
  f[s][t][0] = 0;
  int ans = 0;
  while (!q.empty()) {
    state u = q.front();
    q.pop();
    int x = u.x;
    int y = u.y;
    int st = u.s;
    if (x == s && y == t) tomax(ans, sum[st] - f[x][y][st]);
    for (int i = 0; i < 4; ++i) {
      int xx = x + dx[i];
      int yy = y + dy[i];
      int ss = st;
      if (!judge(xx, yy)) continue;
      if (isdigit(c[xx][yy])) continue;
      if (c[xx][yy] == '#') continue;
      if (c[xx][yy] == 'B') continue;
      for (int j = 0; j < cnt; ++j) {
        if (chk(x, y, xx, yy, j)) ss ^= 1 << j;
      }
      if (!~f[xx][yy][ss]) {
        f[xx][yy][ss] = f[x][y][st] + 1;
        q.push(state(xx, yy, ss));
      }
    }
  }
  return ans;
}
int main() {
  n = read();
  m = read();
  for (int i = 1; i <= n; ++i) {
    scanf("%s", c[i] + 1);
    for (int j = 1; j <= m; ++j) {
      if (c[i][j] == 'S') {
        s = i;
        t = j;
        continue;
      }
      if (isdigit(c[i][j])) {
        int x = c[i][j] - 49;
        p[x] = point(i, j);
        ++cnt;
      }
    }
  }
  for (int i = 0; i < cnt; ++i) v[i] = read();
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= n; ++j) {
      if (c[i][j] == 'B') {
        v[cnt] = -114514;
        p[cnt] = point(i, j);
        ++cnt;
      }
    }
  for (int i = 1; i < (1 << cnt); ++i)
    for (int j = 0; j < cnt; ++j) {
      if ((i >> j) & 1) sum[i] += v[j];
    }
  printf("%d", dp());
  return 0;
}
