#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)); 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 dist = q.front(); q.pop(); if(ci == ei and cj == ej) { return dist; } 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 mat[ti][tj] != '#' and !visited[ti][tj]) { q.push(ti); q.push(tj); q.push(dist + 1); visited[ti][tj] = true; } } } return 1e8; } int main() { cin >> n >> m; vector> d; int drinks = 0; int si, sj, ei, ej; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { cin >> mat[i][j]; if(mat[i][j] == 'S') { si = i; sj = j; } if(mat[i][j] == 'B') { ei = i; ej = j; } if(mat[i][j] == 'D') { d.push_back(make_pair(i, j)); drinks++; } } } int res = 2e9; if(drinks == 1) { res = bfs(si, sj, d[0].first, d[0].second) + bfs(d[0].first, d[0].second, ei, ej); } else if(drinks == 2) { int r1 = bfs(si, sj, d[0].first, d[0].second) + bfs(d[0].first, d[0].second, d[1].first, d[1].second) + bfs(d[1].first, d[1].second, ei, ej); int r2 = bfs(si, sj, d[1].first, d[1].second) + bfs(d[1].first, d[1].second, d[0].first, d[0].second) + bfs(d[0].first, d[0].second, ei, ej); res = min(r1, r2); } else { int r1 = bfs(si, sj, d[0].first, d[0].second) + bfs(d[0].first, d[0].second, d[1].first, d[1].second) + bfs(d[1].first, d[1].second, d[2].first, d[2].second) + bfs(d[2].first, d[2].second, ei, ej); int r2 = bfs(si, sj, d[0].first, d[0].second) + bfs(d[0].first, d[0].second, d[2].first, d[2].second) + bfs(d[2].first, d[2].second, d[1].first, d[1].second) + bfs(d[1].first, d[1].second, ei, ej); int r3 = bfs(si, sj, d[1].first, d[1].second) + bfs(d[1].first, d[1].second, d[0].first, d[0].second) + bfs(d[0].first, d[0].second, d[2].first, d[2].second) + bfs(d[2].first, d[2].second, ei, ej); int r4 = bfs(si, sj, d[1].first, d[1].second) + bfs(d[1].first, d[1].second, d[2].first, d[2].second) + bfs(d[2].first, d[2].second, d[0].first, d[0].second) + bfs(d[0].first, d[0].second, ei, ej); int r5 = bfs(si, sj, d[2].first, d[2].second) + bfs(d[2].first, d[2].second, d[0].first, d[0].second) + bfs(d[0].first, d[0].second, d[1].first, d[1].second) + bfs(d[1].first, d[1].second, ei, ej); int r6 = bfs(si, sj, d[2].first, d[2].second) + bfs(d[2].first, d[2].second, d[1].first, d[1].second) + bfs(d[1].first, d[1].second, d[0].first, d[0].second) + bfs(d[0].first, d[0].second, ei, ej); res = min(min(r1, r2), min(r3, r4)); res = min(res, min(r5, r6)); } if(res > 1e8) { res = -1; } cout << res << endl; return 0; } /* 5 6 #S.### #...## .#..## D..B#. ##.#.. **/