#include <bits/stdc++.h>
using namespace std;
const int INF = 2147483647;
const int maxn = 21;
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {1, -1, 0, 0};
int Map[maxn][maxn], Value[maxn], X[maxn], Y[maxn], XX[maxn], YY[maxn];
int vis[maxn][maxn][260][129], VV[maxn][maxn][260][129],
    inq[maxn][maxn][260][129];
int ans, num, N, M, D;
const int Maxn = 3020120;
char s[30];
struct Point {
  int x, y, z, value, num;
} Q[Maxn];
void BFS(int sx, int sy) {
  int x, y, z, V, u, v, w, NOW, value, NNN, head, tail;
  Q[head = tail = 1] = (Point){sx, sy, 0, 0, 0};
  memset(vis, 0, sizeof(vis));
  vis[sx][sy][0][0] = 1;
  while (head <= tail) {
    x = Q[head].x;
    y = Q[head].y;
    z = Q[head].z;
    V = Q[head].value;
    NOW = Q[head].num;
    inq[x][y][z][V] = 0;
    ++head;
    V--;
    for (int i = 0; i < 4; i++) {
      u = x + dx[i], v = y + dy[i], w = z, value = V, NNN = NOW;
      if (!u || !v || u > N || v > M) continue;
      if (!Map[u][v]) continue;
      for (int k = 1; k <= D; k++)
        if (u == X[k] && v > Y[k] && x == X[k] + 1 ||
            u == X[k] + 1 && v > Y[k] && x == X[k]) {
          w = w ^ (1 << k - 1);
          if (w & (1 << k - 1))
            value += Value[k];
          else
            value -= Value[k];
        }
      for (int k = 1; k <= num; k++) {
        if (u == XX[k] && v > YY[k] && x == XX[k] + 1) NNN = NNN ^ (1 << k - 1);
        if (u == XX[k] + 1 && v > YY[k] && x == XX[k]) NNN = NNN ^ (1 << k - 1);
      }
      if (NNN == 1) NNN = 1;
      if (value > VV[u][v][w][NNN])
        VV[u][v][w][NNN] = value;
      else
        continue;
      if (!vis[u][v][w][NNN])
        Q[++tail] = (Point){u, v, w, value, NNN};
      else
        continue;
      if (u == sx && v == sy && value > ans && NNN == 0) ans = max(ans, value);
      inq[u][v][w][NNN] = 1;
    }
  }
}
int main() {
  cin >> N >> M;
  memset(VV, 235, sizeof(VV));
  for (int i = 1; i <= N; i++) {
    scanf("%s", s + 1);
    for (int j = 1; j <= M; j++) {
      if (s[j] > '0' && s[j] != '#' && s[j] != '.' && s[j] != 'S' &&
          s[j] != 'B')
        X[s[j] - 48] = i, Y[s[j] - 48] = j, D = max(D, s[j] - 48);
      if (s[j] == '.') Map[i][j] = 1;
      if (s[j] == 'S') Map[i][j] = 2;
      if (s[j] == 'B') {
        XX[++num] = i;
        YY[num] = j;
      }
    }
  }
  for (int i = 1; i <= D; i++) scanf("%d", &Value[i]);
  for (int i = 1; i <= N; i++)
    for (int j = 1; j <= M; j++)
      if (Map[i][j] == 2) BFS(i, j);
  cout << ans;
  return 0;
}
