#include <bits/stdc++.h>
using namespace std;
int a, b, c, d, e, f, g[25], h, i, j, k;
char w[25][25];
int F[25][25][1 << 9];
struct node {
  int x, y;
  int step;
  int E;
};
queue<node> que;
vector<pair<int, int> > GG;
node qq[25][25][1 << 9];
int dir[5][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int ALL;
int an;
bool Check(int x, int y) { return w[x][y] == '.' || w[x][y] == 'S'; }
int Make(int x) {
  int ii, jj, kk;
  int R = 0;
  for (ii = 0; ii < GG.size(); ii++)
    if (x & (1 << ii)) R += g[w[GG[ii].first][GG[ii].second] - '0'];
  return R;
}
int main() {
  cin >> a >> b;
  for (i = 1; i <= a; i++) cin >> w[i] + 1;
  int tot = 0;
  node Begin;
  for (i = 1; i <= a; i++)
    for (j = 1; j <= b; j++)
      if (w[i][j] >= '0' && w[i][j] <= '9') {
        ALL ^= 1 << GG.size();
        tot++;
        GG.push_back(make_pair(i, j));
      } else if (w[i][j] == 'B')
        GG.push_back(make_pair(i, j));
      else if (w[i][j] == 'S') {
        Begin.x = i;
        Begin.y = j;
        Begin.E = 0;
        Begin.step = 0;
      }
  memset(F, 1, sizeof(F));
  F[Begin.x][Begin.y][0] = 0;
  for (i = 1; i <= tot; i++) cin >> g[i];
  que.push(Begin);
  while (!que.empty()) {
    node tmp = que.front();
    que.pop();
    for (i = 0; i < 4; i++) {
      node now = tmp;
      now.x += dir[i][0];
      now.y += dir[i][1];
      now.step++;
      if (!Check(now.x, now.y)) continue;
      for (j = 0; j < GG.size(); j++) {
        if (i == 0 || i == 1) break;
        if (i == 3 && now.x == GG[j].first && now.y < GG[j].second)
          now.E ^= 1 << j;
        if (i == 2 && tmp.x == GG[j].first && tmp.y < GG[j].second)
          now.E ^= 1 << j;
      }
      if (F[now.x][now.y][now.E] > now.step) {
        qq[now.x][now.y][now.E] = tmp;
        F[now.x][now.y][now.E] = now.step;
        que.push(now);
      }
    }
  }
  for (i = ALL; i; i = (i - 1) & ALL)
    if (F[Begin.x][Begin.y][i] < (1 << 29))
      an = max(an, Make(i) - F[Begin.x][Begin.y][i]);
  cout << an << endl;
  return 0;
}
