#include <bits/stdc++.h>
using namespace std;
struct nod {
  int x, y, z;
} q[25 * 25 * 1024], no, to;
const int han[4] = {1, -1, 0, 0};
const int lie[4] = {0, 0, 1, -1};
char a[25][25];
int n, m, i, j, z, t, ans, c, tem, sx, sy, w, num;
int f[25][25][1 << 8], val[10], ob[10][2], vis[10];
int news(int x, int y, int yy, int a) {
  for (int i = 0; i < num; i++)
    if (x > ob[i][0] &&
        ((y == ob[i][1] && yy < y) || (yy == ob[i][1] && y < yy)))
      a ^= (1 << i);
  return a;
}
int main() {
  scanf("%d%d", &n, &m);
  num = c = 0;
  for (i = 1; i <= n; i++) {
    scanf("%s", a[i] + 1);
    for (j = 1; j <= m; j++)
      if (a[i][j] >= '1' && a[i][j] <= '8' || a[i][j] == 'B') {
        ob[num][0] = i, ob[num][1] = j;
        if (a[i][j] != 'B') {
          vis[num] = a[i][j] - '0';
          c++;
        }
        num++;
      } else if (a[i][j] == 'S')
        sx = i, sy = j;
  }
  for (i = 1; i <= c; i++) scanf("%d", &val[i]);
  t = w = 0;
  q[++w] = (nod){sx, sy, 0};
  while (t < w) {
    no = q[++t];
    for (i = 0; i < 4; i++) {
      to.x = no.x + han[i];
      to.y = no.y + lie[i];
      if (to.x > 0 && to.x <= n && to.y > 0 && to.y <= m)
        if (a[to.x][to.y] == '.' || a[to.x][to.y] == 'S') {
          to.z = news(to.x, to.y, no.y, no.z);
          if (!f[to.x][to.y][to.z]) {
            f[to.x][to.y][to.z] = f[no.x][no.y][no.z] + 1;
            q[++w] = to;
          }
        }
    }
  }
  ans = 0;
  for (i = 0; i < (1 << num); i++)
    if (f[sx][sy][i] >= 4) {
      int fl = 0;
      for (j = 0, tem = 0; j < num; j++)
        if ((1 << j) & i)
          if (!vis[j]) {
            fl = 1;
            break;
          } else
            tem += val[vis[j]];
      if (!fl) ans = max(ans, tem - f[sx][sy][i]);
    }
  printf("%d\n", ans);
  return 0;
}
