#include <bits/stdc++.h>
using namespace std;
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {1, -1, 0, 0};
struct jzj {
  int x, y;
} P[400];
struct nob {
  int x, y, state;
};
queue<nob> q;
int n, m, sx, sy, tot, dbg;
int F[23][23][2000], sum[2000], val[12];
char mp[23][23];
bool valid(int x, int y) {
  return x > 0 && y > 0 && x <= n && y <= m &&
         (mp[x][y] == '.' || mp[x][y] == 'S');
}
bool judge(int x, int y, int nx, int ny, int i) {
  if (x > nx && x == P[i].x && y < P[i].y) return 1;
  if (x < nx && nx == P[i].x && ny < P[i].y) return 1;
  return 0;
}
int Bfs() {
  q.push(nob{sx, sy, 0});
  memset(F, -1, sizeof F);
  F[sx][sy][0] = 0;
  int ret = 0;
  while (!q.empty()) {
    nob curr = q.front();
    q.pop();
    int x = curr.x, y = curr.y, state = curr.state;
    if (x == sx && y == sy) ret = max(ret, -F[x][y][state] + sum[state]);
    for (int i = 0; i < 4; i++) {
      int nx = x + dx[i], ny = y + dy[i], ns = state;
      if (!valid(nx, ny)) continue;
      for (int j = 1; j <= tot; j++)
        if (judge(x, y, nx, ny, j) && mp[x][y] != 'B') ns ^= 1 << j - 1;
      if (F[nx][ny][ns] == -1) {
        F[nx][ny][ns] = F[x][y][state] + 1;
        q.push(nob{nx, ny, ns});
      }
    }
  }
  return ret;
}
int main() {
  scanf("%d%d", &n, &m);
  for (int i = 1; i <= n; i++) {
    scanf("%s", mp[i] + 1);
    for (int j = 1; j <= m; j++) {
      if (mp[i][j] == 'S') sx = i, sy = j;
      if (isdigit(mp[i][j])) P[mp[i][j] - '0'] = jzj{i, j}, tot++;
    }
  }
  for (int i = 1; i <= tot; i++) scanf("%d", &val[i]);
  for (int S = 1; S <= (1 << tot) - 1; S++)
    for (int i = S; i; i -= (i & -i)) sum[S] += val[(int)log2((i & -i)) + 1];
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= m; j++)
      if (mp[i][j] == 'B') P[++tot] = jzj{i, j};
  return printf("%d\n", Bfs()), 0;
}
