#include <bits/stdc++.h>
using namespace std;
int xx[] = {0, 0, 1, -1};
int yy[] = {-1, 1, 0, 0};
struct trei {
  int v1, v2, v3;
};
trei mk3(int i1, int i2, int i3) {
  trei res;
  res.v1 = i1, res.v2 = i2, res.v3 = i3;
  return res;
}
string sir;
trei que[((1 << 8) * 400 * 10)];
int dp[(22)][(22)][(1 << 9)], value[(22)];
bool viz[(22)][(22)][(1 << 9)];
int xmask[(22)][(22)][5], a[(22)][(22)];
int n, m, nr_good, nrd, i, j, k, stx, sty;
int _mask, result;
void bfs(int p1, int p2, int p3) {
  int k = 0, i, j;
  que[++k] = mk3(p1, p2, p3);
  for (i = 1; i <= k; ++i) {
    int i1 = que[i].v1, i2 = que[i].v2, i3 = que[i].v3;
    for (j = 0; j < 4; ++j) {
      int x2 = i1 + xx[j];
      int y2 = i2 + yy[j];
      int st2 = i3 ^ xmask[i1][i2][j];
      if (a[x2][y2] != 0) continue;
      if (viz[x2][y2][st2] == false) {
        que[++k] = mk3(x2, y2, st2);
        viz[x2][y2][st2] = true;
        dp[x2][y2][st2] = dp[i1][i2][i3] + 1;
      }
    }
  }
}
int main() {
  cin >> n >> m;
  cin.get();
  for (i = 1; i <= n; ++i) {
    cin >> sir;
    for (j = 0; j < m; ++j) {
      if (sir[j] >= '1' && sir[j] <= '8') ++nr_good, a[i][j + 1] = sir[j] - '0';
      if (sir[j] == 'B') a[i][j + 1] = sir[j];
      if (sir[j] == 'S') stx = i, sty = j + 1;
      if (sir[j] == '#') a[i][j + 1] = -1;
    }
  }
  for (i = 1; i <= nr_good; ++i) cin >> value[i];
  for (i = 1; i <= n; ++i)
    for (j = 1; j <= m; ++j)
      if (a[i][j] == 'B') {
        a[i][j] = ++nr_good;
        nrd++;
      }
  for (i = nr_good - 1; i >= (nr_good - 1) - nrd + 1; --i) _mask ^= (1 << i);
  for (i = 0; i <= n + 1; ++i) a[i][0] = a[i][m + 1] = -1;
  for (i = 0; i <= m + 1; ++i) a[0][i] = a[n + 1][i] = -1;
  for (i = 1; i <= n; ++i)
    for (j = 1; j <= m; ++j)
      if (a[i][j] == 0) {
        if (j - 1 > 0 && a[i][j - 1] == 0) {
          for (int col = j - 1, lin = i; lin > 0; --lin)
            if (a[lin][col] >= 1 && a[lin][col] <= 8)
              xmask[i][j][0] ^= (1 << (a[lin][col] - 1));
        }
        if (j + 1 <= m && a[i][j + 1] == 0) {
          for (int col = j, lin = i; lin > 0; --lin)
            if (a[lin][col] >= 1 && a[lin][col] <= 8)
              xmask[i][j][1] ^= (1 << (a[lin][col] - 1));
        }
      }
  viz[stx][sty][0] = true;
  bfs(stx, sty, 0);
  for (i = 0; i < (1 << nr_good); ++i)
    if (viz[stx][sty][i] == true) {
      if ((i & _mask) != 0) continue;
      int suma = -dp[stx][sty][i];
      for (j = 0; j < nr_good - nrd; ++j)
        if (i & (1 << j)) suma += value[j + 1];
      result = max(result, suma);
    }
  cout << result << '\n';
  return 0;
}
