#include <bits/stdc++.h>
using namespace std;
struct arr {
  int x, y, s;
} q[25 * 25 * 257], node[10];
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {1, -1, 0, 0};
char a[25][25];
int f[25][25][257], V[257];
int n, m, i, j, cnt, tot, ans, sx, sy;
void bfs() {
  int h = 0, t = 1;
  q[1] = (arr){sx, sy, 0};
  memset(f, -1, sizeof(f));
  f[sx][sy][0] = 0;
  while (h < t) {
    arr k = q[++h];
    if (k.x == sx && k.y == sy && V[k.s] - f[k.x][k.y][k.s] > ans)
      ans = V[k.s] - f[k.x][k.y][k.s];
    for (int d = 0; d < 4; d++) {
      int x = k.x + dx[d], y = k.y + dy[d], s = k.s;
      if (x < 1 || x > n || y < 1 || y > m) continue;
      if (a[x][y] != '.' && a[x][y] != 'S') continue;
      for (int i = 1; i <= cnt; i++)
        if (!d && node[i].y == k.y && node[i].x < x)
          s ^= (1 << (i - 1));
        else if (d == 1 && node[i].y == y && node[i].x < x)
          s ^= (1 << (i - 1));
      if (f[x][y][s] != -1 && f[x][y][s] <= f[k.x][k.y][k.s] + 1) continue;
      f[x][y][s] = f[k.x][k.y][k.s] + 1;
      q[++t] = (arr){x, y, s};
    }
  }
}
int main() {
  scanf("%d%d", &n, &m);
  for (i = 1; i <= n; i++) {
    scanf("%s", a[i] + 1);
    for (j = 1; j <= m; j++) {
      if (a[i][j] == 'S') sx = i, sy = j;
      if (a[i][j] >= '1' && a[i][j] <= '8')
        node[a[i][j] - '0'] = (arr){i, j, 0}, cnt++;
    }
  }
  for (i = 1; i <= cnt; i++) scanf("%d", &node[i].s);
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++)
      if (a[i][j] == 'B') node[++cnt] = (arr){i, j, -1000000};
  tot = 1 << cnt;
  for (i = 0; i < tot; i++) {
    for (j = 0; j < cnt; j++)
      if (i & (1 << j)) V[i] += node[j + 1].s;
  }
  bfs();
  printf("%d", ans);
}
