#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int N = 20 + 5;
int go[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
int n, m, k;
char s[N][N];
struct Node {
  int x, y, v;
} t[N];
int tot;
int sx, sy;
struct State {
  int x, y, S;
};
int vis[N][N][1 << 10];
int dis[N][N][1 << 10];
inline int calc(int S) {
  int sum = 0;
  for (register int i = 1; i <= k; i++)
    if (S & (1 << (i - 1))) {
      sum += t[i].v;
    }
  return sum;
}
inline int ok(int x, int y, int nx, int ny, int i) {
  if (nx == t[i].x && ny < t[i].y)
    if (x < nx) return 1;
  if (x == t[i].x && y < t[i].y)
    if (x > nx) return 1;
  return 0;
}
int main() {
  cin >> n >> m;
  k = 0;
  for (register int i = 1; i <= n; i++) {
    for (register int j = 1; j <= m; j++) {
      cin >> s[i][j];
      if (s[i][j] == 'S') sx = i, sy = j;
      if (isdigit(s[i][j])) {
        k = max(k, s[i][j] - '0');
        t[s[i][j] - '0'] = {i, j, 0};
      }
    }
  }
  for (register int i = 1; i <= k; i++) cin >> t[i].v;
  for (register int i = 1; i <= n; i++)
    for (register int j = 1; j <= m; j++)
      if (s[i][j] == 'B') {
        t[++k] = {i, j, -inf / 1000};
      }
  queue<State> Q;
  memset(dis, 0x3f, sizeof(dis));
  Q.push(State{sx, sy, 0});
  dis[sx][sy][0] = 0;
  int ans = 0;
  while (Q.size()) {
    State tmp = Q.front();
    Q.pop();
    int x = tmp.x, y = tmp.y, S = tmp.S;
    if (x == sx && y == sy) {
      ans = max(ans, calc(S) - dis[x][y][S]);
    }
    for (register int i = 0; i < 4; i++) {
      int nx = x + go[i][0];
      int ny = y + go[i][1];
      if (nx < 1 || ny < 1 || nx > n || ny > m ||
          (s[nx][ny] != '.' && s[nx][ny] != 'S'))
        continue;
      int T = S;
      for (register int j = 1; j <= k; j++)
        if (ok(x, y, nx, ny, j)) T ^= (1 << (j - 1));
      if (dis[nx][ny][T] == inf) {
        dis[nx][ny][T] = dis[x][y][S] + 1;
        Q.push(State{nx, ny, T});
      }
    }
  }
  cout << ans << endl;
  return 0;
}
