#include <bits/stdc++.h>
using namespace std;
const int INF = (1e9);
int n, m, sx, sy, dp[25][25][1 << 9], done[25][25][1 << 9],
    dy[] = {0, 0, -1, 1}, dx[] = {-1, 1, 0, 0}, val[30];
pair<int, int> obj[30];
char a[25][25];
struct state {
  int val, y, x, mask;
  state() {}
  state(int v, int y, int x, int m) : val(v), y(y), x(x), mask(m) {}
  bool operator<(const state &A) const {
    if (val != A.val) return val < A.val;
    if (y != A.y) return y < A.y;
    if (x != A.x) return x < A.x;
    return mask < A.mask;
  }
};
set<state> S;
int main() {
  scanf("%d%d", &n, &m);
  int k = 0;
  for (int i = 0; i < n; ++i) {
    scanf("%s", a[i]);
    for (int j = 0; j < m; ++j) {
      if (a[i][j] == 'S')
        sx = j, sy = i, a[i][j] = '.';
      else if (isdigit(a[i][j])) {
        int t = a[i][j] - '1';
        k = max(k, t + 1);
        obj[t] = pair<int, int>(i, j);
      }
    }
  }
  for (int i = 0; i < k; ++i) scanf("%d", val + i);
  for (int i = k; i < 30; ++i) val[i] = -INF;
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j)
      if (a[i][j] == 'B') obj[k++] = pair<int, int>(i, j);
  for (int i = 0; i < 25; ++i)
    for (int j = 0; j < 25; ++j) fill(dp[i][j], dp[i][j] + (1 << 9), INF);
  dp[sy][sx][0] = 0;
  S.insert(state(0, sy, sx, 0));
  long long best = 0;
  while (S.size()) {
    state t = *S.begin();
    S.erase(S.begin());
    if (done[t.y][t.x][t.mask]) continue;
    done[t.y][t.x][t.mask] = 1;
    for (int i = 0; i < 4; ++i) {
      int ny = t.y + dy[i], nx = t.x + dx[i];
      if (ny < 0 || nx < 0 || nx >= m || ny >= n) continue;
      if (a[ny][nx] != '.') continue;
      int nmask = t.mask;
      if (ny != t.y) {
        for (int j = 0; j < k; ++j)
          if (max(t.y, ny) == obj[j].first && obj[j].second < t.x)
            nmask ^= (1 << j);
      }
      if (dp[ny][nx][nmask] > 1 + t.val) {
        dp[ny][nx][nmask] = 1 + t.val;
        S.insert(state(1 + t.val, ny, nx, nmask));
      }
    }
  }
  for (int i = 0; i < (1 << 9); ++i) {
    long long t = 0;
    for (int j = 0; j < 9; ++j)
      if (i & (1 << j)) t += val[j];
    best = max(best, t - dp[sy][sx][i]);
  }
  printf("%d\n", (int)best);
  return 0;
}
