#include <bits/stdc++.h>
using namespace std;
const int N = 25;
struct Point {
  int x, y;
  Point(int x = 0, int y = 0) {
    this->x = x;
    this->y = y;
  }
};
struct Data {
  int x, y, maskt, maskb;
  Data(int x = 0, int y = 0, int maskt = 0, int maskb = 0) {
    this->x = x;
    this->y = y;
    this->maskt = maskt;
    this->maskb = maskb;
  }
};
bool cross(Point p, Point l1, Point l2) {
  return (l1.y > p.y) != (l2.y > p.y) &&
         (p.x - l1.x) * (l2.y - l1.y) * (l2.y - l1.y) <
             (p.y - l1.y) * (l2.x - l1.x) * (l2.y - l1.y);
}
int n, m, dist[N][N][1 << 8][1 << 8], val[N];
int t = 0;
int b = 0;
int bombcnt = 0;
char a[N][N];
Point start, treasure[N], bomb[N];
int dx[4] = {0, -1, 0, 1};
int dy[4] = {-1, 0, 1, 0};
bool check(int x, int y) {
  return x >= 1 && x <= n && y >= 1 && y <= m &&
         !(a[x][y] >= '0' && a[x][y] <= '9') && a[x][y] != '#' &&
         a[x][y] != 'B';
}
void bfs(int x, int y) {
  memset(dist, 0x3f, sizeof(dist));
  dist[x][y][0][0] = 0;
  queue<Data> q;
  q.push(Data(x, y, 0, 0));
  while (!q.empty()) {
    Data dt = q.front();
    q.pop();
    for (int i = 0; i < 4; i++) {
      int maskt = dt.maskt;
      int maskb = dt.maskb;
      int curx = dt.x + dx[i];
      int cury = dt.y + dy[i];
      if (check(curx, cury)) {
        for (int j = 1; j <= t; j++) {
          if (cross(treasure[j], Point(dt.x, dt.y), Point(curx, cury)))
            maskt ^= (1 << (j - 1));
        }
        for (int j = 1; j <= bombcnt; j++) {
          if (cross(bomb[j], Point(dt.x, dt.y), Point(curx, cury)))
            maskb ^= (1 << (j - 1));
        }
        if (dist[curx][cury][maskt][maskb] >
            dist[dt.x][dt.y][dt.maskt][dt.maskb] + 1) {
          dist[curx][cury][maskt][maskb] =
              dist[dt.x][dt.y][dt.maskt][dt.maskb] + 1;
          q.push(Data(curx, cury, maskt, maskb));
        }
      }
    }
  }
  int ans = 0;
  for (int maskt = 0; maskt < (1 << 8); maskt++) {
    int cur = 0;
    for (int i = 1; i <= 8; i++) {
      if (maskt & (1 << (i - 1))) cur += val[i];
    }
    ans = max(ans, cur - dist[start.x][start.y][maskt][0]);
  }
  printf("%d", ans);
}
void input() {
  scanf("%d %d", &n, &m);
  getchar();
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      a[i][j] = getchar();
      if (a[i][j] >= '0' && a[i][j] <= '9')
        t = max(t, a[i][j] - '0');
      else if (a[i][j] == 'B')
        b++;
      else if (a[i][j] == 'S')
        start = Point(i, j);
    }
    getchar();
  }
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (a[i][j] >= '0' && a[i][j] <= '9')
        treasure[a[i][j] - '0'] = Point(i, j);
      else if (a[i][j] == 'B')
        bomb[++bombcnt] = Point(i, j);
    }
  }
  for (int i = 1; i <= t; i++) scanf("%d", &val[i]);
}
void solve() { bfs(start.x, start.y); }
int main() {
  input();
  solve();
  return 0;
}
