#include <bits/stdc++.h>
using namespace std;
struct pi {
  int x, y, mask;
  pi(int _x, int _y, int m) {
    x = _x;
    y = _y;
    mask = m;
  }
  pi() {}
} cur, obj[30];
int n, m, cnt, tot;
int path[30][30][1 << 9];
char mp[30][30];
int ax[] = {0, 0, -1, 1};
int ay[] = {-1, 1, 0, 0};
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; i++) scanf("%s", mp[i]);
  int sx, sy, nx, ny;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (mp[i][j] == 'S') {
        sx = i;
        sy = j;
        mp[i][j] = '.';
      } else if (mp[i][j] <= '9' && mp[i][j] >= '0') {
        obj[mp[i][j] - '1'] = pi(i, j, 0);
        cnt++;
      }
    }
  }
  tot = cnt;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (mp[i][j] == 'B') obj[tot++] = pi(i, j, 0);
  memset(path, -1, sizeof(path));
  path[sx][sy][0] = 0;
  queue<pi> q;
  q.push(pi(sx, sy, 0));
  while (!q.empty()) {
    cur = q.front();
    q.pop();
    for (int i = 0; i < 4; i++) {
      nx = cur.x + ax[i];
      ny = cur.y + ay[i];
      if (nx >= 0 && nx < n && ny >= 0 && ny < m && mp[nx][ny] == '.') {
        int mm = cur.mask;
        for (int i = 0; i < tot; i++) {
          if (nx > obj[i].x && (cur.y == obj[i].y && ny == obj[i].y - 1 ||
                                cur.y == obj[i].y - 1 && ny == obj[i].y)) {
            mm ^= 1 << i;
          }
        }
        if (path[nx][ny][mm] == -1 ||
            path[nx][ny][mm] > path[cur.x][cur.y][cur.mask] + 1) {
          path[nx][ny][mm] = path[cur.x][cur.y][cur.mask] + 1;
          q.push(pi(nx, ny, mm));
        }
      }
    }
  }
  int ans = 0, value[30];
  for (int i = 0; i < cnt; i++) cin >> value[i];
  for (int i = 0, k = 0; i < (1 << cnt); i++, k = 0) {
    k -= path[sx][sy][i];
    if (k > 0) continue;
    for (int j = 0; j < cnt; j++)
      if (i & 1 << j) k += value[j];
    ans = max(ans, k);
  }
  cout << ans << endl;
  return 0;
}
