#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1);
const int MAXN = 32;
int n, m;
char grid[MAXN][MAXN];
int prize[MAXN];
struct Collection {
  int x, y;
  int cost;
};
struct Pos {
  int x, y;
  int mask;
};
vector<Collection> colls;
int dis[MAXN][MAXN][256];
int costMask[256];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
bool pass(int x, int y, int x2, int y2, int px, int py) {
  bool check = false;
  if (x == px && y > py) check = true;
  if (x2 == px && y2 > py) check = true;
  if (!check) return false;
  check = false;
  if (x == px - 1 && y > py) check = true;
  if (x2 == px - 1 && y2 > py) check = true;
  if (!check) return false;
  return true;
}
int TestNum;
int main() {
  ios_base::sync_with_stdio(false);
  scanf("%d%d", &n, &m);
  for (int i = 0; i < n; i++) scanf("%s", grid[i]);
  int numTreasure = 0;
  int numBomb = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (isdigit(grid[i][j])) {
        numTreasure++;
      }
      if (grid[i][j] == 'B') {
        numBomb++;
      }
    }
  }
  for (int i = 1; i <= numTreasure; i++) scanf("%d", &prize[i]);
  int sx, sy;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (isdigit(grid[i][j])) {
        colls.push_back({i, j, prize[grid[i][j] - '0']});
      }
      if (grid[i][j] == 'B') {
        colls.push_back({i, j, -100000000});
      }
      if (grid[i][j] == 'S') {
        sx = i, sy = j, grid[i][j] = '.';
      }
    }
  }
  for (int mask = 0; mask < (1 << colls.size()); mask++) {
    if (mask == 0) continue;
    int lowBit = __builtin_ctz(mask);
    costMask[mask] = costMask[mask - (1 << lowBit)] + colls[lowBit].cost;
  }
  memset(dis, 0x3f, sizeof(dis));
  dis[sx][sy][0] = 0;
  queue<Pos> Q;
  Q.push({sx, sy, 0});
  int ans = 0;
  while (Q.size()) {
    const Pos p = Q.front();
    Q.pop();
    if (p.x == sx && p.y == sy) {
      ans = max(ans, costMask[p.mask] - dis[p.x][p.y][p.mask]);
    }
    for (int i = 0; i < 4; i++) {
      Pos t({p.x + dx[i], p.y + dy[i], p.mask});
      if (t.x < 0 || t.y < 0 || t.x == n || t.y == m) continue;
      if (grid[t.x][t.y] != '.') continue;
      for (size_t j = 0; j < colls.size(); j++) {
        if (pass(p.x, p.y, t.x, t.y, colls[j].x, colls[j].y)) {
          t.mask ^= 1 << j;
        }
      }
      if (dis[t.x][t.y][t.mask] > dis[p.x][p.y][p.mask] + 1) {
        dis[t.x][t.y][t.mask] = dis[p.x][p.y][p.mask] + 1;
        Q.push(t);
      }
    }
  }
  cout << ans << endl;
}
