#include <bits/stdc++.h>
using namespace std;
int dp[21][21][1 << 10];
char m[32][32];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
struct Point {
  Point() {}
  Point(int a, int b) : x(a), y(b) {}
  int x, y;
};
struct State {
  State() {}
  State(Point a, int x) : p(a), mask(x) {}
  struct Point p;
  int mask;
};
struct Point obj[10];
int num_obj;
int tr_val[10];
int num_tr = 0;
int value[10];
struct State calc(struct State, struct Point);
int main() {
  int r, c;
  int ma = 0;
  struct Point start;
  cin >> r >> c;
  for (int i = 0; i < r; i++) {
    cin >> m[i];
    for (int j = 0; j < c; j++) {
      if ('1' <= m[i][j] && m[i][j] <= '9') {
        ma = max(m[i][j] - '0', ma);
        tr_val[num_tr] = m[i][j] - '1';
        obj[num_tr++] = Point(i, j);
        num_obj++;
      } else if (m[i][j] == 'S') {
        m[i][j] = '.';
        start = Point(i, j);
      }
    }
  }
  for (int i = 0; i < r; i++)
    for (int j = 0; j < c; j++)
      if (m[i][j] == 'B') obj[num_obj++] = Point(i, j);
  for (int i = 0; i < ma; i++) cin >> value[i];
  memset(dp, -1, sizeof(dp));
  queue<State> q;
  q.push(State(start, 0));
  dp[start.x][start.y][0] = 0;
  while (!q.empty()) {
    State c1 = q.front();
    q.pop();
    State nc;
    for (int i = 0; i < 4; i++) {
      struct Point np;
      np.x = c1.p.x + dx[i], np.y = c1.p.y + dy[i];
      if (0 <= np.x && np.x < r && 0 <= np.y && np.y < c &&
          m[np.x][np.y] == '.') {
        nc = calc(c1, np);
        if (dp[nc.p.x][nc.p.y][nc.mask] == -1 ||
            (dp[nc.p.x][nc.p.y][nc.mask] > dp[c1.p.x][c1.p.y][c1.mask] + 1)) {
          dp[nc.p.x][nc.p.y][nc.mask] = dp[c1.p.x][c1.p.y][c1.mask] + 1;
          q.push(nc);
        }
      }
    }
  }
  int sol = 0;
  for (int i = 0; i < (1 << num_tr); i++) {
    int step = dp[start.x][start.y][i];
    if (step == -1) continue;
    int v = 0;
    for (int j = 0; j < num_tr; j++)
      if (((i >> j) & 1)) v += value[tr_val[j]];
    sol = max(sol, v - step);
  }
  cout << sol << endl;
  return 0;
}
struct State calc(struct State s, struct Point p) {
  struct State ns = s;
  ns.p = p;
  for (int i = 0; i < num_obj; i++) {
    if (s.p.x != p.x) continue;
    if ((s.p.x < obj[i].x) && ((s.p.y == obj[i].y - 1 && p.y == obj[i].y) ||
                               (s.p.y == obj[i].y && p.y == obj[i].y - 1))) {
      ns.mask ^= (1 << i);
    }
  }
  return ns;
};
