#include <bits/stdc++.h>
using namespace std;
const int N = 25;
const int M = 8;
int dp[N][N][1 << M], way[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
struct Node {
  int x, y, mask;
  Node() {}
  Node(int _x, int _y, int _m) : x(_x), y(_y), mask(_m) {}
  int val() { return dp[x][y][mask]; }
};
int n, m, a[N][N], treasure, bomb, val[M], up[N][N];
char str[N][N];
int main() {
  while (scanf("%d %d", &n, &m) != EOF) {
    memset(str, '#', sizeof(str));
    int sx, sy;
    treasure = bomb = 0;
    for (int i = 1; i <= n; i++) {
      scanf("%s", str[i] + 1);
      str[i][m + 1] = '#';
      for (int j = 1; j <= m; j++) {
        if (str[i][j] == 'S')
          sx = i, sy = j, str[i][j] = '.';
        else if (str[i][j] == 'B')
          a[i][j] = bomb++;
        else if (str[i][j] >= '1' && str[i][j] <= '9')
          a[i][j] = str[i][j] - '1', treasure++;
      }
    }
    for (int i = 0; i < treasure; i++) scanf("%d", &val[i]);
    memset(up, 0, sizeof(up));
    for (int i = 1; i < n; i++) {
      for (int j = 1; j <= m; j++) {
        up[i + 1][j] = up[i][j];
        if (str[i][j] == 'B')
          up[i + 1][j] ^= (1 << (a[i][j] + treasure));
        else if (str[i][j] >= '1' && str[i][j] <= '9')
          up[i + 1][j] ^= 1 << a[i][j];
      }
    }
    memset(dp, -1, sizeof(dp));
    queue<Node> que;
    que.push(Node(sx, sy, 0));
    dp[sx][sy][0] = 0;
    while (!que.empty()) {
      Node u = que.front(), v;
      que.pop();
      for (int i = 0; i < 4; i++) {
        v = u;
        v.x += way[i][0];
        v.y += way[i][1];
        if (str[v.x][v.y] != '.') continue;
        if (v.y < u.y)
          v.mask ^= up[u.x][u.y];
        else if (v.y > u.y)
          v.mask ^= up[v.x][v.y];
        if (v.val() == -1) {
          dp[v.x][v.y][v.mask] = u.val() + 1;
          que.push(v);
        }
      }
    }
    int ans = 0;
    for (int i = 0; i < (1 << (bomb + treasure)); i++) {
      if (dp[sx][sy][i] == -1) continue;
      int ret = 0;
      for (int j = treasure; j < treasure + bomb; j++)
        if ((1 << j) & i) ret = 1;
      if (ret) continue;
      for (int j = 0; j < treasure; j++) {
        if ((1 << j) & i) ret += val[j];
      }
      ans = max(ans, ret - dp[sx][sy][i]);
    }
    printf("%d\n", ans);
  }
  return 0;
}
