#include <bits/stdc++.h>
using namespace std;
int f[25][25][1 << 10];
char a[25][25];
struct P {
  int x, y;
} xx[10];
queue<P> q1;
queue<int> q2;
int toap = 0;
int X[4] = {0, 0, 1, -1}, Y[4] = {1, -1, 0, 0}, v[10];
bool operator==(P a, P b) { return a.x == b.x && a.y == b.y; }
int main() {
  memset(f, -1, sizeof(f));
  P st;
  int n, m;
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) {
    scanf("%s", a[i] + 1);
    for (int j = 1; j <= m; j++)
      if (a[i][j] == 'S')
        st = (P){i, j};
      else if (a[i][j] >= 48 && a[i][j] <= 57)
        xx[a[i][j] - '1'] = (P){i, j}, ++toap;
  }
  for (int i = 0; i < toap; i++) scanf("%d", &v[i]);
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (a[i][j] == 'B') xx[toap] = (P){i, j}, v[toap] = -7340033, ++toap;
  int s0 = 0;
  f[st.x][st.y][s0] = 0;
  q1.push(st), q2.push(s0);
  while (q1.size()) {
    P x0 = q1.front();
    int s = q2.front();
    q1.pop(), q2.pop();
    for (int t = 0; t < 4; t++) {
      P x1 = (P){X[t] + x0.x, Y[t] + x0.y};
      if (a[x1.x][x1.y] != '.' && a[x1.x][x1.y] != 'S') continue;
      int ns = s;
      if (X[t] != 0)
        for (int j = 0; j < toap; j++)
          if ((x1.x == xx[j].x && x1.y > xx[j].y && X[t] == -1) ||
              (x0.x == xx[j].x && x0.y > xx[j].y && X[t] == 1))
            ns ^= (1 << j);
      if (f[x1.x][x1.y][ns] == -1)
        f[x1.x][x1.y][ns] = f[x0.x][x0.y][s] + 1, q1.push(x1), q2.push(ns);
    }
  }
  int ans = 0;
  for (int i = 0; i < (1 << toap); i++) {
    int val = -f[st.x][st.y][i];
    if (val > 0) continue;
    for (int j = 0; j < toap; j++)
      if (i >> j & 1) val += v[j];
    ans = max(ans, val);
  }
  printf("%d", ans);
  return 0;
}
