#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  cin >> n >> m;
  vector<string> T(n);
  for (int i = 0; i < n; i++) cin >> T[i];
  int xi, yi, o = 0;
  vector<int> preu;
  int num;
  while (cin >> num) preu.push_back(num);
  vector<int> price(10);
  vector<vector<pair<int, int> > > obj(n);
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (T[i][j] == 'S') {
        xi = i;
        yi = j;
      }
      if (T[i][j] == 'B') {
        obj[i].push_back(pair<int, int>(j, o));
        price[o++] = -100000;
      }
      if (T[i][j] >= '0' && T[i][j] <= '9') {
        obj[i].push_back(pair<int, int>(j, o));
        price[o++] = preu[T[i][j] - '1'];
      }
    }
  }
  vector<vector<vector<int> > > v(
      n, vector<vector<int> >(m, vector<int>(1 << o, 100000)));
  int auxb = 0;
  for (int i = 0; i < obj[xi].size(); i++)
    if (yi < obj[xi][i].first) auxb ^= (1 << obj[xi][i].second);
  queue<pair<pair<int, int>, pair<int, int> > > q;
  q.push(pair<pair<int, int>, pair<int, int> >(pair<int, int>(xi, yi),
                                               pair<int, int>(0, 0)));
  v[xi][yi][0] = 0;
  int xs[] = {0, -1, 0, 1};
  int ys[] = {1, 0, -1, 0};
  while (!q.empty()) {
    int x = q.front().first.first;
    int y = q.front().first.second;
    int b = q.front().second.first;
    int t = q.front().second.second + 1;
    q.pop();
    for (int k = 0; k < 4; ++k) {
      int nx = x + xs[k];
      int ny = y + ys[k];
      int nb = b;
      if (nx >= 0 && ny >= 0 && ny < m && nx < n &&
          (T[nx][ny] == '.' or T[nx][ny] == 'S')) {
        if (x != nx) {
          int Nx = max(x, nx);
          for (int i = 0; i < obj[Nx].size(); i++)
            if (ny < obj[Nx][i].first) nb ^= (1 << obj[Nx][i].second);
        }
        if (v[nx][ny][nb] > t) {
          v[nx][ny][nb] = t;
          q.push(pair<pair<int, int>, pair<int, int> >(pair<int, int>(nx, ny),
                                                       pair<int, int>(nb, t)));
        }
      }
    }
  }
  int millor = 0;
  for (int b = 0; b < 1 << o; b++) {
    int value = -v[xi][yi][b];
    for (int a = 0; a < o; a++)
      if ((b & (1 << a)) != 0) value += price[a];
    millor = max(millor, value);
  }
  cout << millor << endl;
}
