#include <bits/stdc++.h>
void read(int& x) {
  x = 0;
  int flag = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') flag = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
  x *= flag;
}
void read(long long& x) {
  x = 0;
  int flag = 1;
  char ch = getchar();
  while (ch < '0' || ch > '9') {
    if (ch == '-') flag = -1;
    ch = getchar();
  }
  while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
  x *= flag;
}
using namespace std;
const int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};
int n, m, cnt, dp[25][25][260], val[260], sx, sy, ans;
char s[25][25];
struct node {
  int x, y, msk;
  node() {}
  node(int a, int b, int c) { x = a, y = b, msk = c; }
} a[10];
pair<int, int> b[10];
vector<pair<int, int> > c;
bool ok(int x, int y) {
  return x >= 1 && x <= n && y >= 1 && y <= m &&
         (s[x][y] == '.' || s[x][y] == 'S');
}
bool in(int id, int x, int y, int nx, int ny) {
  if (a[id].x == nx && a[id].y > ny && x < nx) return 1;
  if (a[id].x == x && a[id].y > y && x > nx) return 1;
  return 0;
}
void solve() {
  queue<node> q;
  q.push(node(sx, sy, 0));
  memset(dp, -1, sizeof(dp));
  dp[sx][sy][0] = 0;
  while (!q.empty()) {
    node u = q.front();
    q.pop();
    if (u.x == sx && u.y == sy)
      ans = max(ans, val[u.msk] - dp[u.x][u.y][u.msk]);
    for (int k = 0; k <= (int)3; k++) {
      node nx = node(u.x + dx[k], u.y + dy[k], u.msk);
      if (!ok(nx.x, nx.y)) continue;
      for (int i = 0; i <= (int)cnt - 1; i++)
        if (in(i, u.x, u.y, nx.x, nx.y)) nx.msk ^= 1 << i;
      if (dp[nx.x][nx.y][nx.msk] == -1) {
        dp[nx.x][nx.y][nx.msk] = dp[u.x][u.y][u.msk] + 1;
        q.push(nx);
      }
    }
  }
}
int main() {
  read(n), read(m);
  int tmp = 0;
  for (int i = 1; i <= (int)n; i++) {
    scanf("%s", s[i] + 1);
    for (int j = 1; j <= (int)m; j++) {
      if (s[i][j] >= '0' && s[i][j] <= '9')
        b[s[i][j] - '0'] = make_pair(i, j), tmp++;
      else if (s[i][j] == 'B')
        c.push_back(make_pair(i, j));
      else if (s[i][j] == 'S')
        sx = i, sy = j;
    }
  }
  for (int i = 1; i <= (int)tmp; i++) {
    int x;
    read(x);
    a[i - 1] = node(b[i].first, b[i].second, x);
  }
  for (int i = 0; i <= (int)c.size() - 1; i++)
    a[i + tmp] = node(c[i].first, c[i].second, -20000);
  cnt = tmp + (int)c.size();
  for (int msk = 1; msk <= (int)(1 << cnt) - 1; msk++)
    for (int j = 0; j <= (int)cnt - 1; j++)
      if ((1 << j) & msk) val[msk] += a[j].msk;
  solve();
  printf("%d\n", ans);
  return 0;
}
