#include <bits/stdc++.h>
using namespace std;
const int maxn = 25;
const int maxm = 500;
const int maxk = 1 << 9;
const int dx[4] = {1, -1, 0, 0};
const int dy[4] = {0, 0, 1, -1};
int n, m, s, t, cnt, res;
int v[maxm], sum[maxk], f[maxn][maxn][maxk];
char c[maxn][maxn];
struct state {
  int x, y, s;
};
struct point {
  int x, y;
} p[maxm];
bool check(int x, int y, int xx, int yy, int j) {
  if (y == p[j].y && x > p[j].x && y < yy) return true;
  if (yy == p[j].y && xx > p[j].x && yy < y) return true;
  return false;
}
int dp() {
  int ans = 0;
  memset(f, -1, sizeof(f));
  queue<state> q;
  q.push((state){s, t, 0});
  f[s][t][0] = 0;
  while (!q.empty()) {
    state now = q.front();
    q.pop();
    int x = now.x, y = now.y, st = now.s;
    if (x == s && y == t) {
      ans = max(ans, sum[st] - f[x][y][st]);
    }
    for (int i = 0; i < 4; ++i) {
      int xx = x + dx[i], yy = y + dy[i], ss = st;
      if (xx < 1 || xx > n || yy < 1 || yy > m) continue;
      if (c[xx][yy] != 'S' && c[xx][yy] != '.') continue;
      for (int j = 0; j < cnt; ++j) {
        if (check(x, y, xx, yy, j + 1)) ss ^= (1 << j);
      }
      if (f[xx][yy][ss] == -1) {
        f[xx][yy][ss] = f[x][y][st] + 1;
        q.push((state){xx, yy, ss});
      }
    }
  }
  return ans;
}
int main() {
  cin >> n >> m;
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) {
      cin >> c[i][j];
      if (c[i][j] == 'S') {
        s = i;
        t = j;
      } else if (c[i][j] != '.' && c[i][j] != '#' && c[i][j] != 'B') {
        p[c[i][j] - '0'].x = i;
        p[c[i][j] - '0'].y = j;
        ++cnt;
      }
    }
  }
  for (int i = 1; i <= cnt; ++i) cin >> v[i];
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) {
      if (c[i][j] == 'B') {
        p[++cnt].x = i;
        p[cnt].y = j;
        v[cnt] = INT_MIN / 10;
      }
    }
  }
  for (int i = 1; i < (1 << cnt); ++i) {
    for (int j = 0; j < cnt; ++j) {
      if (i & (1 << j)) sum[i] += v[j + 1];
    }
  }
  cout << dp();
  return 0;
}
