#include <bits/stdc++.h>
using namespace std;
int n, m, tot, cnt, Ans;
int Dp[21][21][1 << 8], A[21][2], num[21], val[21];
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
struct Node {
  int x, y, st;
} s;
char S[21][21];
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (ch <= '9' && ch >= '0') {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
int Get_state(int x, int y, int last_y, int last_st) {
  int Now_st = last_st;
  for (int i = 1; i <= tot; i++) {
    if (x > A[i][0] && ((last_y == A[i][1] && y == A[i][1] + 1) ||
                        (last_y == A[i][1] + 1 && y == A[i][1])))
      Now_st ^= (1 << (i - 1));
  }
  return Now_st;
}
void BFS() {
  queue<Node> Q;
  memset(Dp, -1, sizeof(Dp));
  Dp[s.x][s.y][s.st] = 0;
  Q.push(s);
  while (!Q.empty()) {
    Node now = Q.front();
    Q.pop();
    for (int i = 0; i < 4; i++) {
      Node v;
      v.x = now.x + dir[i][0];
      v.y = now.y + dir[i][1];
      if (v.x < 0 || v.x > n || v.y < 0 || v.y > m ||
          (S[v.x][v.y] != '.' && S[v.x][v.y] != 'S'))
        continue;
      v.st = Get_state(v.x, v.y, now.y, now.st);
      if (Dp[v.x][v.y][v.st] != -1) continue;
      Dp[v.x][v.y][v.st] = Dp[now.x][now.y][now.st] + 1;
      Q.push(v);
    }
  }
  for (int i = 0; i < (1 << tot); i++) {
    if (Dp[s.x][s.y][i] == -1) continue;
    int qwer = 0;
    for (int j = 1; j <= tot; j++) {
      if (i & (1 << (j - 1))) {
        if (num[j] == -1) {
          qwer = -1;
          break;
        } else
          qwer += val[num[j]];
      }
    }
    if (qwer == -1) continue;
    Ans = max(Ans, qwer - Dp[s.x][s.y][i]);
  }
  return;
}
int main() {
  n = read();
  m = read();
  for (int i = 1; i <= n; i++) {
    scanf("%s", S[i] + 1);
    for (int j = 1; j <= m; j++) {
      if (S[i][j] == 'B') {
        A[++tot][0] = i;
        A[tot][1] = j;
        num[tot] = -1;
      } else if (S[i][j] >= '1' && S[i][j] <= '8') {
        cnt++;
        A[++tot][0] = i;
        A[tot][1] = j;
        num[tot] = S[i][j] - '0';
      } else if (S[i][j] == 'S') {
        s.x = i;
        s.y = j;
        s.st = 0;
      }
    }
  }
  for (int i = 1; i <= cnt; i++) val[i] = read();
  BFS();
  cout << Ans << endl;
  return 0;
}
