#include <bits/stdc++.h>
using namespace std;
const int dx[4] = {-1, 0, 0, 1}, dy[4] = {0, -1, 1, 0};
struct {
  int x, y, z;
} q[2000010];
int d[21][21][1024], b[21][2], val[21], n, m, t, i, j, k, l, temp, ans;
int xxx, yyy;
char a[21][21];
inline int calc(int z, int x, int y, int nx, int ny) {
  for (int i = 0; i < t; i++)
    if (y < b[i][1] &&
        (x == b[i][0] && nx > b[i][0] || x > b[i][0] && nx == b[i][0]))
      z ^= 1 << i;
  return z;
}
void bfs(int sx, int sy) {
  int x, y, z, nx, ny, nz, l, r, i;
  memset(d, -1, sizeof(d));
  d[sx][sy][0] = 0;
  q[l = r = 1].x = sx, q[1].y = sy, q[1].z = 0;
  while (l <= r) {
    x = q[l].x, y = q[l].y, z = q[l].z, l++;
    for (i = 0; i < 4; i++) {
      nx = x + dx[i], ny = y + dy[i];
      if (a[nx][ny] != '.') continue;
      nz = calc(z, x, y, nx, ny);
      if (d[nx][ny][nz] == -1) {
        d[nx][ny][nz] = d[x][y][z] + 1;
        q[++r].x = nx, q[r].y = ny, q[r].z = nz;
      }
    }
  }
}
int main() {
  cin >> n >> m;
  for (i = 1; i <= n; i++) {
    scanf("%s", a[i] + 1);
    for (j = 1; j <= m; j++) {
      if (a[i][j] == 'S') xxx = i, yyy = j, a[i][j] = '.';
      if (a[i][j] != '.' && a[i][j] != '#' && a[i][j] != 'B') {
        b[a[i][j] - '1'][0] = i, b[a[i][j] - '1'][1] = j;
        t = max(t, a[i][j] - '0');
      }
    }
  }
  for (i = 0; i < t; i++) scanf("%d", &val[i]);
  for (int i = 1; i <= n; ++i)
    for (int j = 1; j <= m; ++j)
      if (a[i][j] == 'B') {
        ++t;
        b[t - 1][0] = i;
        b[t - 1][1] = j;
        val[t - 1] = -1000000;
      }
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++)
      if (a[i][j] == '.' && i == xxx && j == yyy) {
        bfs(i, j);
        for (k = 0; k < 1 << t; k++) {
          if (d[i][j][k] == -1) continue;
          for (temp = l = 0; l < t; l++)
            if ((k >> l) & 1) temp += val[l];
          ans = max(ans, temp - d[i][j][k]);
        }
      }
  cout << ans << endl;
  return 0;
}
