#include <bits/stdc++.h>
using namespace std;
const int MAXSTEP = 500;
const int oo = 999999;
int N, M, X, B;
int Sx, Sy;
int dp[2][20][20][1 << 8];
int id[20][20];
int maskLeft[20][20];
int profit[1 << 8];
int val[8];
char grid[25][25];
int rev[4];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int main() {
  scanf("%d %d", &N, &M);
  for (int i = 0, _n = (int)N; i < _n; i++) scanf("%s", grid[i]);
  for (int i = 0, _n = (int)N; i < _n; i++)
    for (int j = 0, _n = (int)M; j < _n; j++)
      if (grid[i][j] == 'S') {
        Sx = i;
        Sy = j;
        grid[i][j] = '.';
      }
  memset(id, -1, sizeof(id));
  for (int i = 0, _n = (int)N; i < _n; i++)
    for (int j = 0, _n = (int)M; j < _n; j++) {
      if (grid[i][j] >= '1' && grid[i][j] <= '8') {
        id[i][j] = grid[i][j] - '1';
        X++;
        B++;
      }
    }
  for (int i = 0, _n = (int)X; i < _n; i++) scanf("%d", &val[i]);
  for (int i = 0, _n = (int)N; i < _n; i++)
    for (int j = 0, _n = (int)M; j < _n; j++) {
      if (grid[i][j] == 'B') id[i][j] = B++;
    }
  for (int i = 0, _n = (int)N; i < _n; i++)
    for (int j = 0, _n = (int)M; j < _n; j++) {
      for (int k = 0, _n = (int)j; k < _n; k++)
        if (id[i][k] != -1) maskLeft[i][j] |= 1 << id[i][k];
    }
  for (int mask = 0, _n = (int)1 << B; mask < _n; mask++) {
    bool valid = true;
    for (int i = 0; i < X; i++)
      if (mask & (1 << i)) profit[mask] += val[i];
    for (int i = X; i < B; i++)
      if (mask & (1 << i)) valid = false;
    if (!valid) profit[mask] = -oo;
  }
  for (int i = 0, _n = (int)4; i < _n; i++) rev[i] = (i + 2) % 4;
  for (int s = (int)0, _b = (int)MAXSTEP; s <= _b; s++) {
    for (int x = 0, _n = (int)N; x < _n; x++)
      for (int y = 0, _n = (int)M; y < _n; y++)
        for (int mask = 0, _n = (int)1 << B; mask < _n; mask++) {
          int& ref = dp[s & 1][x][y][mask];
          if (x == Sx && y == Sy)
            ref = profit[mask];
          else
            ref = 0;
          if (ref == -oo || s == 0) continue;
          for (int k = 0, _n = (int)4; k < _n; k++) {
            int nx = x + dx[k];
            int ny = y + dy[k];
            if (nx >= 0 && nx < N && ny >= 0 && ny < M && grid[nx][ny] == '.') {
              int newmask = mask;
              if (k == 0) newmask ^= maskLeft[x][y];
              if (k == 2) newmask ^= maskLeft[nx][ny];
              int nv = dp[(s - 1) & 1][nx][ny][newmask] - 1;
              if (ref < nv) ref = nv;
            }
          }
        }
  }
  int res = 0;
  for (int k = 0, _n = (int)4; k < _n; k++)
    res = max(res, dp[MAXSTEP & 1][Sx][Sy][0]);
  printf("%d\n", res);
}
