#include <bits/stdc++.h>
#pragma warning(disable : 4996)
using namespace std;
int n, m;
char s[33][33];
int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1}, v[10], mp[33][33],
    dp[33][33][1 << 10], tc, bc, obx[10], oby[10];
queue<int> q;
int check(int x, int y, int xx, int yy) {
  int re = 0;
  if (x == xx) {
    for (int i = 0; i < (int)(bc); ++i) {
      double temy = (double)(x - obx[i]) * 42.0 / 43.0 + oby[i];
      if (x > obx[i] && temy >= (double)min(y, yy) &&
          temy <= (double)max(y, yy))
        re |= (1 << i);
    }
  } else {
    for (int i = 0; i < (int)(bc); ++i) {
      double temx = (double)(y - oby[i]) * 43.0 / 42.0 + obx[i];
      if (y > oby[i] && temx >= (double)min(x, xx) &&
          temx <= (double)max(x, xx))
        re |= (1 << i);
    }
  }
  return re;
}
void BFS(int sx, int sy) {
  dp[sx][sy][0] = 0;
  q.push(sx), q.push(sy), q.push(0);
  while (!q.empty()) {
    int x = q.front();
    q.pop();
    int y = q.front();
    q.pop();
    int st = q.front();
    q.pop();
    for (int i = 0; i < (int)(4); ++i) {
      if (x + dx[i] >= 0 && y + dy[i] >= 0 && x + dx[i] < n && y + dy[i] < m &&
              s[x + dx[i]][y + dy[i]] == '.' ||
          s[x + dx[i]][y + dy[i]] == 'S') {
        int tems = st ^ check(x, y, x + dx[i], y + dy[i]);
        if (dp[x + dx[i]][y + dy[i]][tems] < 0) {
          dp[x + dx[i]][y + dy[i]][tems] = dp[x][y][st] + 1;
          q.push(x + dx[i]), q.push(y + dy[i]), q.push(tems);
        }
      }
    }
  }
}
int go(int x) {
  int re = 0;
  for (int i = 0; i < (int)(tc); ++i) {
    if (x & (1 << i)) re += v[i];
  }
  return re;
}
int main() {
  int i, j, k, x, y, z, ca = 1, re = 0, sx, sy;
  scanf("%d%d", &(n), &(m));
  for (int i = 0; i < (int)(n); ++i) scanf("%s", (s[i]));
  for (int i = 0; i < (int)(n); ++i)
    for (int j = 0; j < (int)(m); ++j)
      if (s[i][j] >= '0' && s[i][j] <= '9')
        obx[s[i][j] - '0' - 1] = i, oby[s[i][j] - '0' - 1] = j, tc++;
      else if (s[i][j] == 'S')
        sx = i, sy = j;
  bc = tc;
  for (int i = 0; i < (int)(n); ++i)
    for (int j = 0; j < (int)(m); ++j)
      if (s[i][j] == 'B') obx[bc] = i, oby[bc++] = j;
  for (int i = 0; i < (int)(tc); ++i) scanf("%d", &(v[i]));
  memset(dp, -1, sizeof(dp));
  BFS(sx, sy);
  for (int i = 0; i < (int)((1 << tc)); ++i) {
    if (dp[sx][sy][i] >= 0) re = max(re, go(i) - dp[sx][sy][i]);
  }
  printf("%d\n", (re));
  return 0;
}
