#include
#include
#include
#include
using namespace std;
int n, m;
char mat[105][105];
int bfs(int si, int sj, int ei, int ej) {
queue q;
q.push(si);
q.push(sj);
q.push(0);
vector> visited(n, vector(m, false));
visited[si][sj] = true;
int di[] = {-1, 1, 0, 0};
int dj[] = {0, 0, -1, 1};
while(!q.empty()) {
int ci = q.front();
q.pop();
int cj = q.front();
q.pop();
int cekor = q.front();
q.pop();
if(ci == ei and cj == ej) {
return cekor;
}
for(int i = 0; i < 4; i++) {
int ti = ci + di[i];
int tj = cj + dj[i];
if(ti >= 0 and ti < n and tj >= 0 and tj < m and !visited[ti][tj] and mat[ti][tj] != '#'){
q.push(ti);
q.push(tj);
q.push(cekor + 1);
visited[ti][tj] = true;
}
}
}
}
int main()
{
cin >> n >> m;
vector> drinks;
int si = 0, sj = 0, bi = 0, bj = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
cin >> mat[i][j];
if(mat[i][j] == 'D') {
drinks.push_back(make_pair(i, j));
}
if(mat[i][j] == 'S') {
si = i;
sj = j;
}
if(mat[i][j] == 'B') {
bi = i;
bj = j;
}
}
}
vector permutacija;
for(int i = 0; i < drinks.size(); i++) {
permutacija.push_back(i);
}
int sz = permutacija.size();
int res = 1000;
do {
int path = 0;
for(int i = 0; i < permutacija.size(); i++) {
if(i == 0) {
path += bfs(si, sj, drinks[permutacija[i]].first, drinks[permutacija[i]].second);
}
else {
path += bfs(drinks[permutacija[i]].first, drinks[permutacija[i]].second, drinks[permutacija[i - 1]].first, drinks[permutacija[i - 1]].second);
}
}
path += bfs(drinks[permutacija[sz - 1]].first, drinks[permutacija[sz - 1]].second, bi, bj);
res = min(res ,path);
} while(next_permutation(permutacija.begin(), permutacija.end()));
cout << res << endl;
return 0;
}
/*
CX..
C...
K = 2
**/