#include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 0, 1, -1, 1, -1, 1, -1}, dy[] = {-1, 1, 0, 0, 1, -1, -1, 1};
void run();
int main() {
  ios::sync_with_stdio(0);
  cout << fixed << setprecision(16);
  run();
}
int n, m;
string M[22];
map<tuple<int, int, int>, int> dis;
pair<int, int> pos[10];
int o;
int t;
int idx[22][22];
int val[10];
const int inf = 1 << 30;
void run() {
  cin >> n >> m;
  int si, sj;
  for (int i = (0); i < (n); ++i) {
    cin >> M[i];
    for (int j = (0); j < (m); ++j) {
      if (isdigit(M[i][j]) || M[i][j] == 'B')
        idx[i][j] = o, pos[o++] = make_pair(i, j);
      if (isdigit(M[i][j])) t++;
      if (M[i][j] == 'S') si = i, sj = j;
    }
  }
  for (int i = (0); i < (t); ++i) cin >> val[i];
  queue<tuple<int, int, int> > q;
  for (int i = (0); i < (n); ++i)
    for (int j = (0); j < (m); ++j)
      for (int m = (0); m < (1 << o); ++m) dis[make_tuple(i, j, m)] = inf;
  dis[make_tuple(si, sj, 0)] = 0;
  q.push(make_tuple(si, sj, 0));
  while (!q.empty()) {
    int i = get<0>(q.front());
    int j = get<1>(q.front());
    int mask = get<2>(q.front());
    q.pop();
    for (int dd = 0; dd < 4; ++dd) {
      int ii = i + dx[dd], jj = j + dy[dd];
      if (ii >= n || ii < 0 || jj >= m || jj < 0 ||
          (M[ii][jj] != '.' && M[ii][jj] != 'S'))
        continue;
      int newm = mask;
      if (j == jj) {
        int a = min(i, ii);
        for (int k = 0; k < o; ++k)
          if (pos[k].first == a && pos[k].second < j) newm ^= (1 << k);
      }
      if (dis[make_tuple(ii, jj, newm)] == inf) {
        dis[make_tuple(ii, jj, newm)] = dis[make_tuple(i, j, mask)] + 1;
        q.push(make_tuple(ii, jj, newm));
      }
    }
  }
  int ans = 0;
  for (int mask = (0); mask < (1 << o); ++mask) {
    int value = 0;
    bool valid = 1;
    for (int k = (0); k < (o); ++k) {
      if (!(mask & (1 << k))) continue;
      if (M[pos[k].first][pos[k].second] == 'B') {
        valid = 0;
        break;
      } else
        value += val[M[pos[k].first][pos[k].second] - '1'];
    }
    if (!valid) continue;
    value -= dis[make_tuple(si, sj, mask)];
    ans = max(ans, value);
  }
  cout << ans << "\n";
}
