#include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 0, -1, 1};
int dy[] = {1, -1, 0, 0};
struct el {
  int x, y;
  int mask, c;
  el() {}
  el(int _x, int _y, int _mask, int _c) {
    x = _x;
    y = _y;
    mask = _mask;
    c = _c;
  }
  bool operator<(el b) const { return c > b.c; }
};
int n, m;
int nums;
char a[32][32];
pair<int, int> b[16];
int c[16];
int d[32][32][1 << 8];
priority_queue<el> pq;
int ans;
void read() {
  int i, j;
  nums = 0;
  scanf("%d%d", &n, &m);
  for (i = 0; i < n; i++) {
    scanf("%s", a[i]);
    for (j = 0; j < m; j++) {
      if (a[i][j] >= '1' && a[i][j] <= '9') {
        if (a[i][j] - '1' > nums) {
          nums = a[i][j] - '1';
        }
        b[a[i][j] - '1'] = make_pair(i, j);
      }
    }
  }
  for (i = 0; i <= nums; i++) {
    scanf("%d", &c[i]);
  }
}
inline void psh(int x, int y, int mask, int c) {
  if (d[x][y][mask] == -1 || d[x][y][mask] > c) {
    d[x][y][mask] = c;
    pq.push(el(x, y, mask, c));
  }
}
inline int get(int mask, int x, int y) {
  int i;
  for (i = 0; i <= nums; i++) {
    if (b[i].first >= x && b[i].second == y) {
      mask ^= (1 << i);
    }
  }
  return mask;
}
inline void checkAns(int r, int mask) {
  r = -r;
  for (int i = 0; i <= nums; i++) {
    if (mask & (1 << i)) {
      r += c[i];
    }
  }
  if (r >= ans) {
    ans = r;
  }
}
void solve() {
  int i, j;
  int sx, sy;
  sx = sy = 0;
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      if (a[i][j] == 'B') {
        ++nums;
        b[nums] = make_pair(i, j);
        c[nums] = -1234567;
      }
      if (a[i][j] == 'S') {
        sx = i;
        sy = j;
      }
    }
  }
  a[sx][sy] = '.';
  ans = 0;
  memset(d, -1, sizeof d);
  int nmask;
  psh(sx, sy, 0, 0);
  while (!pq.empty()) {
    int x = pq.top().x;
    int y = pq.top().y;
    int mask = pq.top().mask;
    int c = pq.top().c;
    pq.pop();
    if (d[x][y][mask] < c) {
      continue;
    }
    if (x == sx && y == sy) {
      checkAns(c, mask);
    }
    for (int i = 0; i < 4; i++) {
      int nx = x + dx[i];
      int ny = y + dy[i];
      if (nx >= 0 && ny >= 0 && nx < n && ny < m &&
          (a[nx][ny] == '.' || a[nx][ny] == 'S')) {
        nmask = mask;
        if (i == 0) {
          nmask = get(mask, x, y);
        } else {
          if (i == 1) {
            nmask = get(mask, nx, ny);
          }
        }
        psh(nx, ny, nmask, c + 1);
      }
    }
  }
  printf("%d\n", ans);
}
int main() {
  read();
  solve();
  return 0;
}
