#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int SUM = 0, ff = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') ff = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') {
    SUM = (SUM << 3) + (SUM << 1) + (ch ^ 48);
    ch = getchar();
  }
  return SUM * ff;
}
const int N = 30;
const int inf = 2000000;
const int xx[] = {0, 0, 1, -1};
const int yy[] = {1, -1, 0, 0};
int gx[N], gy[N], val[N];
int sum[1 << 10];
char g[N][N];
int n, m, cnt, mx;
int sx, sy;
int dp[N][N][1 << 10];
struct state {
  int x, y, s;
  state(int _x = 0, int _y = 0, int _s = 0) {
    x = _x;
    y = _y;
    s = _s;
  }
};
inline bool in(int x, int y, int nx, int ny, int i) {
  if (nx == gx[i] && ny < gy[i] && x < nx) return 1;
  if (x == gx[i] && y < gy[i] && x > nx) return 1;
  return 0;
}
inline int BFS() {
  queue<state> q;
  q.push(state(sx, sy, 0));
  int ans = 0;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      for (int s = 0; s < mx; s++) dp[i][j][s] = -1;
  dp[sx][sy][0] = 0;
  while (!q.empty()) {
    state now = q.front();
    q.pop();
    int x = now.x, y = now.y, s = now.s;
    if (x == sx && y == sy) {
      ans = max(ans, sum[s] - dp[x][y][s]);
    }
    for (int i = 0; i < 4; i++) {
      int cx = x + xx[i], cy = y + yy[i], cs = s;
      if (cx < 1 || cx > n || cy < 1 || cy > m ||
          (g[cx][cy] != '.' && g[cx][cy] != 'S'))
        continue;
      for (int j = 1; j <= cnt; j++)
        if (in(x, y, cx, cy, j)) cs ^= 1 << (j - 1);
      if (dp[cx][cy][cs] == -1) {
        dp[cx][cy][cs] = dp[x][y][s] + 1;
        q.push(state(cx, cy, cs));
      }
    }
  }
  return ans;
}
int main() {
  n = read(), m = read();
  for (int i = 1; i <= n; i++) scanf("%s\n", g[i] + 1);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      char ch = g[i][j];
      if (ch == 'S') {
        sx = i, sy = j;
      } else if (ch >= '0' && ch <= '9') {
        int t = ch - '0';
        gx[t] = i, gy[t] = j;
        cnt++;
      }
    }
  for (int i = 1; i <= cnt; i++) val[i] = read();
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++) {
      char ch = g[i][j];
      if (ch == 'B') {
        cnt++;
        gx[cnt] = i, gy[cnt] = j;
        val[cnt] = -inf;
      }
    }
  mx = 1 << cnt;
  for (int s = 1; s < mx; s++) {
    for (int i = 1; i <= cnt; i++)
      if (s & (1 << (i - 1))) sum[s] += val[i];
  }
  printf("%d\n", BFS());
  return 0;
}
