#include <bits/stdc++.h>
using namespace std;
const int N = 25;
const int inf = 1e7 + 7;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int n, m, t, v[N], sr, sc;
int object[N][N], cellmask[N][N], dist[N][N][1 << 10];
char board[N][N];
void solve() {
  for (int i = 1; i <= (int)(n); ++i)
    for (int j = 1; j <= (int)(m); ++j)
      for (int s = 0; s < (int)(1 << (t + 1)); ++s) dist[i][j][s] = inf;
  dist[sr][sc][0] = 0;
  queue<pair<pair<int, int>, int> > Q;
  Q.push(make_pair(make_pair(sr, sc), 0));
  while (!Q.empty()) {
    auto p = Q.front();
    Q.pop();
    for (int dir = 0; dir < (int)(4); ++dir) {
      int tx = p.first.first + dx[dir];
      int ty = p.first.second + dy[dir];
      if (tx < 1 || tx > n || ty < 1 || ty > m) continue;
      if (board[tx][ty] != '.' && board[tx][ty] != 'S') continue;
      int msk = p.second;
      if (dir == 0) msk ^= cellmask[tx][ty];
      if (dir == 1) msk ^= cellmask[p.first.first][p.first.second];
      if (dist[p.first.first][p.first.second][p.second] + 1 <
          dist[tx][ty][msk]) {
        dist[tx][ty][msk] = dist[p.first.first][p.first.second][p.second] + 1;
        Q.push(make_pair(make_pair(tx, ty), msk));
      }
    }
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= (int)(n); ++i)
    for (int j = 1; j <= (int)(m); ++j) scanf(" %c", &board[i][j]);
  for (int i = 1; i <= (int)(n); ++i)
    for (int j = 1; j <= (int)(m); ++j)
      if (isdigit(board[i][j])) {
        t++;
        object[i][j] = int(board[i][j] - '0');
      }
  for (int i = 1; i <= (int)(t); ++i) scanf("%d", &v[i]);
  for (int i = 1; i <= (int)(n); ++i)
    for (int j = 1; j <= (int)(m); ++j)
      if (board[i][j] == 'B') {
        t++;
        object[i][j] = t, v[t] = -inf;
      }
  for (int i = 1; i <= (int)(n); ++i)
    for (int j = 1; j <= (int)(m); ++j)
      if (board[i][j] == 'S') {
        sr = i, sc = j;
      }
  for (int i = 1; i <= (int)(n); ++i)
    for (int j = 1; j <= (int)(m); ++j)
      if (object[i][j]) {
        for (int k = j + 1; k <= m; ++k) cellmask[i][k] |= (1 << object[i][j]);
      }
  solve();
  int ret = 0;
  for (int s = 0; s < (int)(1 << (t + 1)); ++s) {
    int val = -dist[sr][sc][s];
    for (int i = 1; i <= (int)(t); ++i)
      if (s >> i & 1) val += v[i];
    ret = max(ret, val);
  }
  printf("%d\n", ret);
  return 0;
}
