#include <bits/stdc++.h>
const double pi = acos(-1);
const int MOD = 1e9 + 7;
const int INF = 1e9 + 7;
const int MAXN = 1e2 + 5;
const double eps = 1e-9;
using namespace std;
int n, m, c[MAXN][MAXN], dp[MAXN][MAXN][1 << 8], e[MAXN * MAXN * MAXN];
int f[MAXN * MAXN * MAXN], g[MAXN * MAXN * MAXN], pr[MAXN], p[1 << 8];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
char s[MAXN][MAXN];
int main() {
  pair<int, int> st;
  int t = 0, b = 0;
  scanf("%d", &(n)), scanf("%d", &(m));
  for (int i = 0; i < n; i++) {
    scanf("%s", s[i]);
    for (int j = 0; j < m; j++)
      if (s[i][j] == 'S')
        st = {i, j}, s[i][j] = '.';
      else if (s[i][j] > '0' && s[i][j] < '9') {
        t++;
        for (int k = 0; k < i; k++) c[k][j] |= (1 << (s[i][j] - '1'));
      }
  }
  for (int i = 0; i < (t); i++) scanf("%d", &(pr[i]));
  b = t;
  for (int i = 0; i < (1 << t); i++)
    for (int j = 0; j < t; j++)
      if ((i >> j) & 1) p[i] += pr[j];
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (s[i][j] == 'B') {
        for (int k = 0; k < i; k++) c[k][j] |= (1 << b);
        b++;
      }
  int l = 0, r = 1;
  e[1] = 0, f[1] = st.first, g[1] = st.second;
  memset(dp, 6, sizeof dp);
  dp[st.first][st.second][0] = 0;
  while (l < r) {
    int x = f[++l], y = g[l], z = e[l];
    int cur = dp[x][y][z];
    for (int i = 0; i < 4; i++) {
      int nx = x + dx[i], ny = y + dy[i], k = z;
      if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
      if (s[nx][ny] != '.') continue;
      if (y != ny) k ^= c[nx][min(y, ny)];
      if (cur + 1 < dp[nx][ny][k]) {
        dp[nx][ny][k] = cur + 1;
        f[++r] = nx, g[r] = ny, e[r] = k;
      }
    }
  }
  int ans = 0;
  for (int i = 0; i < (1 << t); i++)
    ans = max(ans, p[i] - dp[st.first][st.second][i]);
  printf("%d\n", (ans));
  return 0;
}
