#include <bits/stdc++.h>
using namespace std;
int d[21][21][256][256];
struct info {
  int x, y;
} b[10], t[10];
struct node {
  int x, y, ts, bs, f;
  node() {}
  node(int xx, int yy, int tt, int bb, int ff) {
    x = xx, y = yy, ts = tt, bs = bb, f = ff;
  }
} q[200050];
char s[22][22];
int va[22];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int main() {
  int n, m;
  scanf("%d%d", &n, &m);
  int c1 = 0, c2 = 0;
  int bx, by;
  for (int i = 0; i < n; ++i) {
    scanf(" %s", s[i]);
    for (int j = 0; j < m; ++j) {
      if (s[i][j] >= '1' && s[i][j] <= '9') {
        ++c1;
        int x = s[i][j] - '0';
        t[x].x = i;
        t[x].y = j;
      }
      if (s[i][j] == 'B') {
        c2++;
        b[c2].x = i;
        b[c2].y = j;
      }
      if (s[i][j] == 'S') {
        bx = i;
        by = j;
      }
    }
  }
  for (int i = 1; i <= c1; ++i) scanf("%d", &va[i]);
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j)
      for (int x = 0; x < (1 << c1); ++x)
        for (int y = 0; y < (1 << c2); ++y) d[i][j][x][y] = 1000000000;
  d[bx][by][0][0] = 0;
  int tail = 0;
  q[tail++] = node(bx, by, 0, 0, -1);
  for (int i = 0; i < tail; ++i) {
    for (int j = 0; j < 4; ++j) {
      int step = d[q[i].x][q[i].y][q[i].ts][q[i].bs];
      int x = dx[j] + q[i].x;
      int y = dy[j] + q[i].y;
      int f = j;
      if (q[i].f == 0 && f == 1) continue;
      if (q[i].f == 1 && f == 0) continue;
      if (q[i].f == 2 && f == 3) continue;
      if (q[i].f == 3 && f == 2) continue;
      if (x < 0 || x >= n || y < 0 || y >= m) continue;
      if (s[x][y] != 'S' && s[x][y] != '.') continue;
      int ts = q[i].ts;
      int bs = q[i].bs;
      if (f >= 2) {
        if (d[x][y][ts][bs] > step + 1) {
          d[x][y][ts][bs] = step + 1;
          q[tail++] = node(x, y, ts, bs, f);
        }
      } else {
        for (int k = 1; k <= c1; ++k) {
          if (((q[i].y) < (y) ? (q[i].y) : (y)) == t[k].y && q[i].x > t[k].x) {
            ts ^= (1 << (k - 1));
          }
        }
        for (int k = 1; k <= c2; ++k) {
          if (((q[i].y) < (y) ? (q[i].y) : (y)) == b[k].y && q[i].x > b[k].x) {
            bs ^= (1 << (k - 1));
          }
        }
        if (d[x][y][ts][bs] > step + 1) {
          d[x][y][ts][bs] = step + 1;
          q[tail++] = node(x, y, ts, bs, f);
        }
      }
    }
  }
  int pos, ans = 0;
  for (int i = 0; i < (1 << c1); ++i) {
    int sum = 0;
    for (int j = 0; j < c1; ++j) {
      if ((1 << j) & i) {
        sum += va[j + 1];
      }
    }
    if (ans < sum - d[bx][by][i][0]) {
      ans = sum - d[bx][by][i][0];
      pos = i;
    }
  }
  printf("%d\n", ans);
}
