#include <bits/stdc++.h>
using namespace std;
int n, m, ax, ay, dx[4] = {1, -1, 0, 0}, dy[4] = {0, 0, 1, -1}, val[55],
                  dp[55][55][1 << 9];
int kk;
char c[25];
bool cz[25][25];
int zd[25][25];
struct node {
  int x, y, s;
};
queue<node> q;
void zy(int x, int y, int s) {
  for (int k = 0; k < 4; k++) {
    int px = x + dx[k], py = y + dy[k], ps = s;
    if (px < 0 || px >= n || py < 0 || py >= m || !cz[px][py]) continue;
    if (k <= 1) {
      int xp = x - k;
      for (int j = y; j < m; j++)
        if (zd[xp][j]) ps ^= (1 << (zd[xp][j] - 1));
    }
    if (dp[px][py][ps] == -1) {
      dp[px][py][ps] = dp[x][y][s] + 1;
      q.push((node){px, py, ps});
    }
  }
}
int main() {
  memset(dp, -1, sizeof(dp));
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) {
    scanf("%s", c);
    for (int j = 0; j < m; j++) {
      cz[i][j] = (c[j] == '.' || c[j] == 'S');
      if (c[j] == 'S') ax = i, ay = j;
      if (c[j] == 'B')
        zd[i][j] = -1;
      else if (c[j] >= '0' && c[j] <= '9')
        kk = max(kk, zd[i][j] = c[j] - '0');
    }
  }
  for (int i = 1; i <= kk; i++) scanf("%d", &val[i]);
  for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
      if (zd[i][j] == -1) val[zd[i][j] = ++kk] = -2e8;
  q.push((node){ax, ay, 0});
  dp[ax][ay][0] = 0;
  while (!q.empty()) {
    node u = q.front();
    q.pop();
    zy(u.x, u.y, u.s);
  }
  int ans = -1;
  for (int i = 0; i < (1 << kk); i++)
    if (dp[ax][ay][i] != -1) {
      int ss = 0;
      for (int j = 0; j < kk; j++)
        if ((i >> j) & 1) ss += val[j + 1];
      ans = max(ans, -dp[ax][ay][i] + ss);
    }
  return printf("%d", ans), 0;
}
