#include <bits/stdc++.h>
using namespace std;
const double PI = 3.14159265359;
int dp[21][21][256][256];
int n, m;
int bcnt, tcnt;
string f[21];
int sx, sy;
int bomb_x[9];
int trash_x[9];
vector<int> bomb_on_y[21];
vector<int> trash_on_y[21];
int price[9];
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
int ans;
struct state {
  state() {}
  state(short x, short y, short tmask, short bmask)
      : x(x), y(y), tmask(tmask), bmask(bmask) {}
  short x;
  short y;
  short tmask;
  short bmask;
};
void invert(short &mask, int bit) {
  if (mask & (1 << bit))
    mask &= ~(1 << bit);
  else
    mask |= (1 << bit);
}
void bfs() {
  queue<state> q;
  q.push(state(sx, sy, 0, 0));
  while (!q.empty()) {
    state v = q.front();
    q.pop();
    int x = v.x;
    int y = v.y;
    for (int i = 0; i < 4; ++i) {
      int nx = x + dx[i];
      int ny = y + dy[i];
      if (nx < 0 || nx >= n) continue;
      if (ny < 0 || ny >= m) continue;
      if (f[nx][ny] != '.' && f[nx][ny] != 'S') continue;
      state to(nx, ny, v.tmask, v.bmask);
      if (y != ny) {
        int cy = min(y, ny);
        for (int j = 0; j < bomb_on_y[cy].size(); ++j)
          if (bomb_x[bomb_on_y[cy][j]] > nx) invert(to.bmask, bomb_on_y[cy][j]);
        for (int j = 0; j < trash_on_y[cy].size(); ++j)
          if (trash_x[trash_on_y[cy][j]] > nx)
            invert(to.tmask, trash_on_y[cy][j]);
      }
      if (to.x == sx && to.y == sy && to.tmask == 0 && to.bmask == 0) continue;
      if (dp[to.x][to.y][to.tmask][to.bmask] != 0) continue;
      dp[to.x][to.y][to.tmask][to.bmask] = dp[v.x][v.y][v.tmask][v.bmask] + 1;
      q.push(to);
    }
  }
}
int main() {
  cin >> n >> m;
  for (int i = 0; i < n; ++i) {
    cin >> f[i];
    for (int j = 0; j < m; ++j) {
      if (f[i][j] == 'S')
        sx = i, sy = j;
      else if (f[i][j] == 'B') {
        bomb_on_y[j].push_back(bcnt);
        bomb_x[bcnt] = i;
        bcnt++;
      } else if (isdigit(f[i][j])) {
        trash_on_y[j].push_back(f[i][j] - '1');
        trash_x[f[i][j] - '1'] = i;
        tcnt++;
      }
    }
  }
  for (int i = 0; i < tcnt; ++i) cin >> price[i];
  bfs();
  for (int tmask = 0; tmask < (1 << tcnt); ++tmask) {
    int a = dp[sx][sy][tmask][0];
    if (a != 0) {
      int b = 0;
      for (int i = 0; i < tcnt; ++i)
        if (tmask & (1 << i)) b += price[i];
      ans = max(ans, b - a);
    }
  }
  cout << ans;
  return 0;
}
