#include <bits/stdc++.h>
using namespace std;
const int maxn = 25;
const int maxm = 9;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};
int n, m, k, kk, sx, sy, ql, qr;
char s[maxn][maxn];
int l[maxn][maxn], val[maxn], id[maxn];
int dp[maxn][maxn][1 << maxm];
pair<pair<int, int>, int> que[maxn * maxn * (1 << maxm) + 5];
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 0; i < (n); i++) {
    scanf("%s", s[i]);
    for (int j = 0; j < (m); j++) {
      if (s[i][j] == 'S') sx = i, sy = j;
      if (j) l[i][j] = l[i][j - 1];
      if ((s[i][j] >= '1' && s[i][j] <= '8') || s[i][j] == 'B') {
        if (s[i][j] >= '1' && s[i][j] <= '8') id[s[i][j] - '1'] = k, kk++;
        l[i][j] |= (1 << k);
        k++;
      }
    }
  }
  for (int i = 0; i < (k); i++) val[i] = -300;
  for (int i = 0; i < (kk); i++) scanf("%d", &val[id[i]]);
  for (int i = 0; i < (n); i++)
    for (int j = 0; j < (m); j++)
      for (int mask = 0; mask < (1 << k); mask++) dp[i][j][mask] = -1;
  dp[sx][sy][0] = 0;
  que[qr++] = make_pair(make_pair(sx, sy), 0);
  while (ql < qr) {
    int x = que[ql].first.first, y = que[ql].first.second,
        mask = que[ql].second;
    ql++;
    for (int d = 0; d < (4); d++) {
      int nx = x + dx[d], ny = y + dy[d], nmask = mask;
      if (nx < 0 || nx >= n || ny < 0 || ny >= m ||
          (s[nx][ny] != '.' && s[nx][ny] != 'S'))
        continue;
      if (!(d & 1)) nmask ^= l[max(x, nx)][y];
      if (dp[nx][ny][nmask] < 0) {
        dp[nx][ny][nmask] = dp[x][y][mask] + 1;
        que[qr++] = make_pair(make_pair(nx, ny), nmask);
      }
    }
  }
  int ans = 0;
  for (int mask = 0; mask < (1 << k); mask++)
    if (dp[sx][sy][mask] >= 0) {
      bool ok = true;
      int cur = 0;
      for (int i = 0; i < (k); i++)
        if ((mask >> i) & 1) {
          if (val[i] == -300)
            ok = false;
          else
            cur += val[i];
        }
      if (ok) ans = max(ans, cur - dp[sx][sy][mask]);
    }
  printf("%d\n", ans);
  return 0;
}
