#include <bits/stdc++.h>
using namespace std;
const int inf = (int)1e9;
const double INF = 1e12, EPS = 1e-9;
int h, w, n, a[20], mask[20][20];
string in[20];
bool v[5][400][1 << 8];
int main() {
  int sx, sy;
  cin >> h >> w;
  for (int i = 0; i < (int)h; i++) {
    cin >> in[i];
    for (int j = 0; j < (int)w; j++) {
      if (isdigit(in[i][j])) {
        for (int k = 0; k < (int)i + 1; k++) mask[k][j] |= 1 << in[i][j] - '1';
        n++;
      }
      if (in[i][j] == 'S') {
        sy = i, sx = j;
        in[i][j] = '.';
      }
    }
  }
  for (int i = 0; i < (int)n; i++) cin >> a[i];
  for (int i = 0; i < (int)h; i++)
    for (int j = 0; j < (int)w; j++)
      if (in[i][j] == 'B') {
        for (int k = 0; k < (int)i + 1; k++) mask[k][j] |= 1 << n;
        a[n++] = -100000;
      }
  int ans = 0;
  queue<pair<pair<int, int>, pair<int, int> > > q;
  q.push(make_pair(make_pair(0, 4), make_pair(sy * w + sx, 0)));
  while (!q.empty()) {
    int y = q.front().second.first / w, x = q.front().second.first % w;
    int bit = q.front().second.second;
    int cost = q.front().first.first, prev = q.front().first.second;
    q.pop();
    if (v[prev][y * w + x][bit]) continue;
    v[prev][y * w + x][bit] = 1;
    if (y == sy && x == sx) {
      int score = cost;
      for (int i = 0; i < (int)n; i++)
        if (bit & 1 << i) score += a[i];
      ans = max(ans, score);
    }
    for (int d = 0; d < (int)4; d++) {
      const int dy[] = {-1, 0, 1, 0}, dx[] = {0, -1, 0, 1};
      int ny = y + dy[d], nx = x + dx[d];
      if (ny < 0 || nx < 0 || ny >= h || nx >= w || in[ny][nx] != '.') continue;
      if (prev < 4 && dy[prev] + dy[d] == 0 && dx[prev] + dx[d] == 0) continue;
      int nbit = bit;
      if (d == 3) nbit ^= mask[y][x];
      if (d == 1) nbit ^= mask[ny][nx];
      q.push(make_pair(make_pair(cost - 1, d), make_pair(ny * w + nx, nbit)));
    }
  }
  cout << ans << endl;
  return 0;
}
