#include <bits/stdc++.h>
using namespace std;
char a[30][30];
int n, m;
vector<pair<int, int> > sp;
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int d[23][23][(1 << 8) + 10];
int p[22 * 22 * (1 << 8)][3];
int get(int x1, int y1, int x2, int y2, int x3, int y3) {
  int X1 = x2 - x1;
  int Y1 = y2 - y1;
  int X2 = x3 - x1;
  int Y2 = y3 - y1;
  return X1 * Y2 - X2 * Y1;
}
int cost[10];
int main() {
  memset(d, -1, sizeof(d));
  srand(time(NULL));
  scanf("%d%d", &n, &m);
  for (int i = (0); i < (n); ++i) scanf("%s", a[i]);
  int x = -1, y = -1;
  for (int i = (0); i < (n); ++i)
    for (int j = (0); j < (m); ++j) {
      if (a[i][j] == 'S') {
        x = i;
        y = j;
      } else if ((a[i][j] == 'B') || ((a[i][j] >= '1') && (a[i][j] <= '8')))
        sp.push_back(make_pair(i, j));
    }
  int in = 0;
  while (scanf("%d", &cost[in]) != EOF) in++;
  p[0][0] = x;
  p[0][1] = y;
  p[0][2] = 0;
  d[x][y][0] = 0;
  int l = 0, r = 0;
  while (l <= r) {
    int x = p[l][0];
    int y = p[l][1];
    int mask = p[l++][2];
    int dist = d[x][y][mask];
    for (int k = (0); k < (4); ++k) {
      int nx = x + dx[k];
      int ny = y + dy[k];
      if ((nx < 0) || (nx >= n) || (ny < 0) || (ny >= m)) continue;
      if ((a[nx][ny] != 'S') && (a[nx][ny] != '.')) continue;
      int nmask = mask;
      for (int c = (0); c < (sp.size()); ++c) {
        int v1 = get(x, y, nx, ny, sp[c].first, sp[c].second);
        int v2 = get(x, y, nx, ny, sp[c].first + 53, sp[c].second + 55);
        int v3 = get(sp[c].first, sp[c].second, sp[c].first + 53,
                     sp[c].second + 55, x, y);
        int v4 = get(sp[c].first, sp[c].second, sp[c].first + 53,
                     sp[c].second + 55, nx, ny);
        if ((v1 * v2 < 0) && (v3 * v4 < 0)) nmask ^= (1 << c);
      }
      if (d[nx][ny][nmask] == -1) {
        d[nx][ny][nmask] = dist + 1;
        r++;
        p[r][0] = nx;
        p[r][1] = ny;
        p[r][2] = nmask;
      }
    }
  }
  int res = 0;
  for (int mask = (1); mask < ((1 << sp.size())); ++mask) {
    if (d[x][y][mask] != -1) {
      bool f = true;
      int now = 0;
      for (int i = (0); i < (sp.size()); ++i)
        if ((mask >> i) & 1)
          if (a[sp[i].first][sp[i].second] == 'B')
            f = false;
          else
            now += cost[a[sp[i].first][sp[i].second] - '0' - 1];
      if (f) res = max(res, now - d[x][y][mask]);
    }
  }
  cout << res << endl;
}
