#include <bits/stdc++.h>
template <typename T>
inline void read(T& t) {
  int f = 0, c = getchar();
  t = 0;
  while (!isdigit(c)) f |= c == '-', c = getchar();
  while (isdigit(c)) t = t * 10 + c - 48, c = getchar();
  if (f) t = -t;
}
template <typename T1, typename T2>
inline void read(T1& t1, T2& t2) {
  read(t1);
  read(t2);
}
template <typename T1, typename T2, typename T3>
inline void read(T1& t1, T2& t2, T3& t3) {
  read(t1, t2);
  read(t3);
}
template <typename T1, typename T2, typename T3, typename T4>
inline void read(T1& t1, T2& t2, T3& t3, T4& t4) {
  read(t1, t2, t3);
  read(t4);
}
const int inf = 2e6 + 207;
int dp[30][30][1 << 10];
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {1, -1, 0, 0};
int gx[30], gy[30], val[30];
int sum[1 << 10];
char G[30][30];
int n, m, t;
int sx, sy;
struct State {
  int x, y, k;
  explicit State(int xx, int yy, int kk) : x(xx), y(yy), k(kk) {}
  State() : x(0), y(0), k(0) {}
};
inline bool in(int x, int y, int nx, int ny, int i) {
  if (nx == gx[i] && ny < gy[i])
    if (x < nx) return 1;
  if (x == gx[i] && y < gy[i])
    if (x > nx) return 1;
  return 0;
}
inline int bfs() {
  std::queue<State> q;
  q.emplace(sx, sy, 0);
  int ans = 0;
  for (int i = (1); i <= (n); ++i)
    for (int j = (1); j <= (m); ++j)
      for (int k = (0); k <= ((1 << t)); ++k) dp[i][j][k] = -1;
  dp[sx][sy][0] = 0;
  while (!q.empty()) {
    State curr = q.front();
    q.pop();
    int x = curr.x, y = curr.y, k = curr.k;
    if (x == sx && y == sy) ans = std::max(ans, sum[k] - dp[x][y][k]);
    for (int i = (0); i <= (3); ++i) {
      int nx = x + dx[i], ny = y + dy[i];
      if (nx < 1 || nx > n || ny < 1 || ny > m ||
          (G[nx][ny] != '.' && G[nx][ny] != 'S'))
        continue;
      int nk = k;
      for (int j = (1); j <= (t); ++j)
        if (in(x, y, nx, ny, j)) nk ^= 1 << (j - 1);
      if (dp[nx][ny][nk] == -1) {
        dp[nx][ny][nk] = dp[x][y][k] + 1;
        q.emplace(nx, ny, nk);
      }
    }
  }
  return ans;
}
int main() {
  read(n, m);
  for (int i = (1); i <= (n); ++i) scanf("%s", G[i] + 1);
  for (int i = (1); i <= (n); ++i)
    for (int j = (1); j <= (m); ++j) {
      char c = G[i][j];
      if (c == 'S') {
        sx = i;
        sy = j;
      } else if (c != '#' && c != '.' && c != 'B') {
        gx[c - 48] = i;
        gy[c - 48] = j;
        ++t;
      }
    }
  for (int i = (1); i <= (t); ++i) read(val[i]);
  for (int i = (1); i <= (n); ++i)
    for (int j = (1); j <= (m); ++j) {
      char c = G[i][j];
      if (c == 'B') {
        gx[++t] = i;
        gy[t] = j;
        val[t] = -inf;
      }
    }
  for (int S = 1; S < 1 << t; ++S) {
    for (int i = (1); i <= (t); ++i)
      if (1 << (i - 1) & S) sum[S] += val[i];
  }
  int ans = bfs();
  printf("%d\n", ans);
  return 0;
}
