#include <bits/stdc++.h>
using namespace std;
int d[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
char s[25][25];
int dp[25][25][1 << 8];
pair<int, int> p[8];
int val[8];
int ridx[8];
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  int sx, sy;
  for (int i = 1; i <= n; i++) {
    scanf("%s", s[i] + 1);
    for (int j = 1; j <= m; j++) {
      if (s[i][j] == 'S') {
        sx = i, sy = j;
        s[i][j] = '.';
      }
    }
  }
  int idx1 = 0, idx2 = 0;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if ('1' <= s[i][j] && s[i][j] <= '8') {
        p[idx1++] = make_pair(i, j);
        ridx[idx1 - 1] = s[i][j] - '1';
      }
    }
  }
  idx2 = idx1;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (s[i][j] == 'B') p[idx1++] = make_pair(i, j);
    }
  }
  for (int i = 0; i < idx2; i++) scanf("%d", &val[i]);
  memset(dp, -1, sizeof(dp));
  dp[sx][sy][0] = 0;
  queue<pair<pair<int, int>, int> > q;
  q.push(make_pair(make_pair(sx, sy), 0));
  while (!q.empty()) {
    int x = q.front().first.first, y = q.front().first.second,
        a = q.front().second;
    q.pop();
    for (int i = 0; i < 4; i++) {
      int vx = x + d[i][0], vy = y + d[i][1], va = a;
      if (1 <= vx && vx <= n && 1 <= vy && vy <= m && s[vx][vy] == '.') {
        for (int j = 0; j < idx1; j++) {
          if (y < p[j].second &&
              ((i == 0 && x == p[j].first) || (i == 1 && vx == p[j].first)))
            va ^= (1 << j);
        }
        if (dp[vx][vy][va] == -1) {
          dp[vx][vy][va] = dp[x][y][a] + 1;
          q.push(make_pair(make_pair(vx, vy), va));
        }
      }
    }
  }
  int ans = 0;
  for (int i = 0; i < (1 << idx1); i++) {
    if (dp[sx][sy][i] == -1) continue;
    bool ok = 1;
    int sum = 0;
    for (int j = 0; j < idx1; j++) {
      if (j >= idx2 && ((i >> j) & 1)) {
        ok = 0;
        break;
      }
      if ((i >> j) & 1) sum += val[ridx[j]];
    }
    if (ok) ans = max(ans, sum - dp[sx][sy][i]);
  }
  printf("%d\n", ans);
}
