#include <bits/stdc++.h>
using namespace std;
int id[25][25];
char M[25][25];
int n, m;
int dist[25][25][(1 << 9)];
int Vx[] = {-1, 1, 0, 0};
int Vy[] = {0, 0, 1, -1};
bool out(int x, int y) {
  return min(x, y) < 0 || x >= n || y >= m ||
         (M[x][y] != '.' && M[x][y] != 'S');
}
void bfs(int x, int y) {
  memset(dist, -1, sizeof dist);
  queue<int> Q;
  dist[x][y][0] = 0;
  Q.push(x), Q.push(y), Q.push(0);
  while (!Q.empty()) {
    x = Q.front();
    Q.pop();
    y = Q.front();
    Q.pop();
    int mask = Q.front();
    Q.pop();
    for (int k = 0; k < 4; k++) {
      int xx = x + Vx[k], yy = y + Vy[k];
      if (out(xx, yy)) continue;
      int m2 = mask;
      if (k == 2) {
        for (int i = x - 1; i >= 0; i--)
          if (id[i][y] != -1) m2 ^= (1 << id[i][y]);
      }
      if (k == 3) {
        for (int i = x - 1; i >= 0; i--)
          if (id[i][yy] != -1) m2 ^= (1 << id[i][yy]);
      }
      if (dist[xx][yy][m2] == -1) {
        dist[xx][yy][m2] = dist[x][y][mask] + 1;
        Q.push(xx), Q.push(yy), Q.push(m2);
      }
    }
  }
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; i++) scanf(" %s", M[i]);
  memset(id, -1, sizeof id);
  int cnt = 0;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (M[i][j] >= '0' && M[i][j] <= '9') {
        id[i][j] = M[i][j] - '1';
        cnt++;
      }
  int good = cnt;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (M[i][j] == 'B') {
        id[i][j] = cnt++;
      }
  int x, y;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (M[i][j] == 'S') x = i, y = j;
  bfs(x, y);
  int val[20];
  for (int i = 0; i < good; i++) cin >> val[i];
  int ret = 0;
  for (int i = 0; i < (1 << good); i++) {
    int sum = 0;
    for (int j = 0; j < good; j++)
      if (1 & (i >> j)) sum += val[j];
    if (dist[x][y][i] != -1) ret = max(ret, sum - dist[x][y][i]);
  }
  cout << ret << endl;
  return 0;
}
