#include <bits/stdc++.h>
using namespace std;
vector<string> enframe(vector<string> abc, char impassable) {
  string huhu(((int)(abc[0]).size()) + 2, impassable);
  for (int(i) = 0; (i) < (((int)(abc).size())); ++(i))
    abc[i] = impassable + abc[i] + impassable;
  abc.insert(abc.begin(), huhu);
  abc.push_back(huhu);
  return abc;
}
int dp[24][24][1 << 8];
int dr[] = {1, 0, -1, 0};
int dc[] = {0, 1, 0, -1};
int code[24][24];
int code_to_r[24];
int code_to_c[24];
int main() {
  int row, col;
  cin >> row >> col;
  vector<string> peta;
  for (int(i) = 0; (i) < (row); ++(i)) {
    string str;
    cin >> str;
    peta.push_back(str);
  }
  peta = enframe(peta, '#');
  row += 2;
  col += 2;
  int sr, sc;
  int ns = 0;
  int nt = 0;
  for (int(i) = 0; (i) < (row); ++(i))
    for (int(j) = 0; (j) < (col); ++(j)) {
      code[i][j] = -1;
      if (peta[i][j] == 'S') {
        sr = i;
        sc = j;
      }
      if (peta[i][j] == 'B' || (peta[i][j] >= '1' && peta[i][j] <= '9')) {
        code[i][j] = ns++;
        code_to_r[code[i][j]] = i;
        code_to_c[code[i][j]] = j;
        if (peta[i][j] != 'B') ++nt;
      }
    }
  for (int(i) = 0; (i) < (24); ++(i))
    for (int(j) = 0; (j) < (24); ++(j))
      for (int(k) = 0; (k) < ((1 << 8)); ++(k)) dp[i][j][k] = -1;
  queue<pair<pair<int, int>, int> > q;
  q.push(make_pair(make_pair(sr, sc), 0));
  dp[sr][sc][0] = 0;
  while (!q.empty()) {
    int r = q.front().first.first;
    int c = q.front().first.second;
    int mask = q.front().second;
    q.pop();
    int right = 1;
    int left = 3;
    for (int(dir) = 0; (dir) < (4); ++(dir)) {
      int nr = r + dr[dir];
      int nc = c + dc[dir];
      int nmask = mask;
      if (peta[nr][nc] != '.' && peta[nr][nc] != 'S') {
        continue;
      }
      if (dir == right) {
        for (int mr = nr + 1; mr < row; ++mr) {
          if (code[mr][nc] != -1) {
            nmask ^= (1 << code[mr][nc]);
          }
        }
      }
      if (dir == left) {
        for (int mr = nr + 1; mr < row; ++mr) {
          if (code[mr][c] != -1) {
            nmask ^= (1 << code[mr][c]);
          }
        }
      }
      if (dp[nr][nc][nmask] == -1) {
        dp[nr][nc][nmask] = dp[r][c][mask] + 1;
        q.push(make_pair(make_pair(nr, nc), nmask));
      }
    }
  }
  vector<int> valval;
  for (int(i) = 0; (i) < (nt); ++(i)) {
    int x;
    cin >> x;
    valval.push_back(x);
  }
  long long best = 0;
  for (int i = 0; i < (1 << ns); ++i) {
    int ok = 1;
    long long sumval = 0;
    for (int j = 0; j < ns; ++j)
      if (i & (1 << j)) {
        int r = code_to_r[j];
        int c = code_to_c[j];
        if (peta[r][c] == 'B') {
          ok = 0;
          break;
        }
        sumval += valval[peta[r][c] - '1'];
      }
    if (ok && dp[sr][sc][i] != -1) best = max((best), (sumval - dp[sr][sc][i]));
  }
  cout << best << endl;
  return 0;
}
