#include <bits/stdc++.h>
const int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}, N = 30;
int n, m, T, B, f[N][N][1 << 8], ans, sum[1 << 8], q[(1 << 8) * N * N][3], sx,
    sy, st[N][N], v[N], bit[10];
char map[N][N];
bool vis[N][N][1 << 8];
void BFS() {
  int h = 1, t = 0;
  vis[sx][sy][0] = true;
  q[++t][1] = sx;
  q[t][2] = sy;
  for (; h <= t;) {
    const int x = q[h][1], y = q[h][2], sta = q[h][0];
    ++h;
    for (int i = 0; i < 4; ++i) {
      const int nx = x + d[i][0], ny = y + d[i][1];
      if (nx < 0 || nx == n || ny < 0 || ny == m || map[nx][ny] != '.')
        continue;
      int nst = sta;
      if (i == 1)
        nst ^= st[nx][ny];
      else if (i == 0)
        nst ^= st[x][y];
      if (vis[nx][ny][nst]) continue;
      vis[nx][ny][nst] = true;
      q[++t][0] = nst;
      q[t][1] = nx;
      q[t][2] = ny;
      f[nx][ny][q[t][0]] = f[x][y][sta] + 1;
    }
  }
}
int main() {
  scanf("%d%d\n", &n, &m);
  for (int i = 0; i <= 8; ++i) bit[i] = 1 << i;
  for (int i = 0; i < n; ++i) {
    for (int j = 0; j < m; ++j) {
      scanf("%c", &map[i][j]);
      if (map[i][j] == 'S')
        sx = i, sy = j, map[i][j] = '.';
      else if ('0' < map[i][j] && map[i][j] < '9') {
        ++T;
        for (int k = j + 1; k < m; ++k) st[i][k] |= bit[map[i][j] - '1'];
      }
    }
    scanf("\n");
  }
  for (int i = 0; i < T; ++i) scanf("%d", v + i);
  for (int i = 0; i < bit[T]; ++i)
    for (int j = 0; j < T; ++j)
      if (i & bit[j]) sum[i] += v[j];
  B = T;
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j)
      if (map[i][j] == 'B') {
        for (int k = j + 1; k < m; ++k) st[i][k] |= bit[B];
        ++B;
      }
  BFS();
  for (int i = 0; i < bit[T]; ++i)
    if (vis[sx][sy][i]) ans = std::max(ans, sum[i] - f[sx][sy][i]);
  printf("%d\n", ans);
}
