#include <bits/stdc++.h>
using namespace std;
int X, Y, K;
string board[30];
int object[30][30];
int cellmask[30][30];
bool empty[30][30];
int cost[10];
queue<int> q;
int dist[30][30][(1 << 8)];
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
int func(int sx, int sy) {
  int i, j, mask;
  for ((i) = 0; (i) < (int)(X); (i)++)
    for ((j) = 0; (j) < (int)(Y); (j)++)
      for ((mask) = 0; (mask) < (int)((1 << K)); (mask)++)
        dist[i][j][mask] = (1 << 29);
  dist[sx][sy][0] = 0;
  q.push(sx);
  q.push(sy);
  q.push(0);
  while (!q.empty()) {
    int x = q.front();
    q.pop();
    int y = q.front();
    q.pop();
    mask = q.front();
    q.pop();
    int dir;
    for ((dir) = 0; (dir) < (int)(4); (dir)++) {
      int x2 = x + dx[dir];
      int y2 = y + dy[dir];
      if (!(x2 >= 0 && x2 < X && y2 >= 0 && y2 < Y && empty[x2][y2])) continue;
      int mask2 = mask;
      if (dir == 0) mask2 ^= cellmask[x][y];
      if (dir == 1) mask2 ^= cellmask[x2][y2];
      if (dist[x2][y2][mask2] == (1 << 29)) {
        dist[x2][y2][mask2] = dist[x][y][mask] + 1;
        q.push(x2);
        q.push(y2);
        q.push(mask2);
      }
    }
  }
  int ans = 0;
  for ((mask) = 0; (mask) < (int)((1 << K)); (mask)++) {
    if (dist[sx][sy][mask] == (1 << 29)) continue;
    int tmp = -dist[sx][sy][mask];
    for ((i) = 0; (i) < (int)(K); (i)++)
      if (mask & (1 << i)) tmp += cost[i];
    ans = max(ans, tmp);
  }
  return ans;
}
int main(void) {
  int i, j, k;
  cin >> X >> Y;
  for ((i) = 0; (i) < (int)(X); (i)++) cin >> board[i];
  for ((i) = 0; (i) < (int)(X); (i)++)
    for ((j) = 0; (j) < (int)(Y); (j)++) object[i][j] = -1;
  int cnt = 0;
  for ((i) = 0; (i) < (int)(X); (i)++)
    for ((j) = 0; (j) < (int)(Y); (j)++)
      if (board[i][j] >= '1' && board[i][j] <= '8') {
        object[i][j] = board[i][j] - '1';
        cnt++;
      }
  K = cnt;
  for ((i) = 0; (i) < (int)(X); (i)++)
    for ((j) = 0; (j) < (int)(Y); (j)++)
      if (board[i][j] == 'B') {
        object[i][j] = K;
        K++;
      }
  for ((i) = 0; (i) < (int)(cnt); (i)++) cin >> cost[i];
  for (i = cnt; i < K; i++) cost[i] = -1000000;
  for ((i) = 0; (i) < (int)(X); (i)++)
    for ((j) = 0; (j) < (int)(Y); (j)++)
      empty[i][j] = (board[i][j] == '.' || board[i][j] == 'S');
  int sx = 0, sy = 0;
  for ((i) = 0; (i) < (int)(X); (i)++)
    for ((j) = 0; (j) < (int)(Y); (j)++)
      if (board[i][j] == 'S') {
        sx = i;
        sy = j;
      }
  for ((i) = 0; (i) < (int)(X); (i)++)
    for ((j) = 0; (j) < (int)(Y); (j)++)
      if (object[i][j] != -1)
        if (i > 0)
          for (k = j + 1; k < Y; k++) cellmask[i - 1][k] |= (1 << object[i][j]);
  int ans = func(sx, sy);
  cout << ans << endl;
  return 0;
}
