#include <bits/stdc++.h>
using namespace std;
int n, m, c, c_, refc[10];
char mp[25][25];
int p[25][25];
int val[10], px[10], py[10], sx, sy;
int dx[5] = {0, 1, 0, -1, 0}, dy[5] = {0, 0, -1, 0, 1};
int dp[25][25][1 << 8], sum[1 << 8], ans;
struct state {
  int x, y, st;
};
int cross(int a, int b, int c, int d, int k) {
  if (b >= py[k] || d >= py[k]) return 0;
  if ((a == px[k] && c < a) || (c == px[k] && a < c)) return 1;
  return 0;
}
void bfs() {
  queue<state> q;
  q.push((state){sx, sy, 0});
  state now;
  int nx, ny, s, ax, ay, as;
  memset(dp, -1, sizeof(dp));
  dp[sx][sy][0] = 0;
  while (!q.empty()) {
    now = q.front();
    q.pop();
    nx = now.x;
    ny = now.y;
    s = now.st;
    if (nx == sx && ny == sy) ans = max(ans, sum[s] - dp[nx][ny][s]);
    for (int i = 1; i <= 4; ++i) {
      ax = nx + dx[i];
      ay = ny + dy[i];
      as = s;
      if (ax <= 0 || ax > n || ay <= 0 || ay > m ||
          (mp[ax][ay] != '.' && mp[ax][ay] != 'S'))
        continue;
      for (int j = 0; j < c; ++j)
        if (cross(nx, ny, ax, ay, j)) as ^= (1 << j);
      if (dp[ax][ay][as] == -1) {
        dp[ax][ay][as] = dp[nx][ny][s] + 1;
        q.push((state){ax, ay, as});
      }
    }
  }
}
int main() {
  ios::sync_with_stdio(0);
  cin >> n >> m;
  for (int i = 1; i <= n; ++i) cin >> (mp[i] + 1);
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) {
      if (mp[i][j] == '#')
        p[i][j] = 1;
      else if (mp[i][j] == 'S')
        sx = i, sy = j;
      else if (isdigit(mp[i][j]))
        px[mp[i][j] - 49] = i, py[mp[i][j] - 49] = j, ++c;
    }
  }
  for (int i = 0; i < c; ++i) cin >> val[i];
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      if (mp[i][j] == 'B') val[c] = -10000000, px[c] = i, py[c++] = j;
  for (int i = 1; i < (1 << c); ++i)
    for (int j = 0; j < c; ++j)
      if (i & (1 << j)) sum[i] += val[j];
  bfs();
  cout << ans << endl;
  return 0;
}
