Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- int n, m;
- char mat[105][105];
- int bfs(pair<int, int> S, pair<int, int> E) {
- vector<vector<bool>> visited(n, vector<bool>(m, false));
- int si = S.first, sj = S.second;
- int ei = E.first, ej = E.second;
- visited[si][sj] = true;
- queue<int> q;
- q.push(si);
- q.push(sj);
- q.push(0);
- 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;
- }
- if(ci + 1 < n and mat[ci + 1][cj] != '#' and !visited[ci + 1][cj]) {
- q.push(ci + 1);
- q.push(cj);
- q.push(dist + 1);
- visited[ci + 1][cj] = true;
- }
- if(ci - 1 >= 0 and mat[ci - 1][cj] != '#' and !visited[ci - 1][cj]) {
- q.push(ci - 1);
- q.push(cj);
- q.push(dist + 1);
- visited[ci - 1][cj] = true;
- }
- if(cj + 1 < m and mat[ci][cj + 1] != '#' and !visited[ci][cj + 1]) {
- q.push(ci);
- q.push(cj + 1);
- q.push(dist + 1);
- visited[ci][cj + 1] = true;
- }
- if(cj - 1 >= 0 and mat[ci][cj - 1] != '#' and !visited[ci][cj - 1]) {
- q.push(ci);
- q.push(cj - 1);
- q.push(dist + 1);
- visited[ci][cj - 1] = true;
- }
- }
- return 1000;
- }
- int main()
- {
- cin >> n >> m;
- pair<int, int> S, E;
- vector<pair<int, int>> D;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cin >> mat[i][j];
- if(mat[i][j] == 'S') {
- S = make_pair(i, j);
- }
- if(mat[i][j] == 'B') {
- E = make_pair(i, j);
- }
- if(mat[i][j] == 'D') {
- D.push_back(make_pair(i, j));
- }
- }
- }
- int res = 1000;
- if(D.size() == 1) {
- res = bfs(S, D[0]) + bfs(D[0], E);
- }
- else if(D.size() == 2) {
- res = min(res, bfs(S, D[0]) + bfs(D[0], D[1]) + bfs(D[1], E));
- res = min(res, bfs(S, D[1]) + bfs(D[1], D[0]) + bfs(D[0], E));
- }
- else {
- res = min(res, bfs(S, D[0]) + bfs(D[0], D[1]) + bfs(D[1], D[2]) + bfs(D[2], E));
- res = min(res, bfs(S, D[0]) + bfs(D[0], D[2]) + bfs(D[2], D[1]) + bfs(D[1], E));
- res = min(res, bfs(S, D[1]) + bfs(D[1], D[0]) + bfs(D[0], D[2]) + bfs(D[2], E));
- res = min(res, bfs(S, D[1]) + bfs(D[1], D[2]) + bfs(D[2], D[0]) + bfs(D[0], E));
- res = min(res, bfs(S, D[2]) + bfs(D[2], D[0]) + bfs(D[0], D[1]) + bfs(D[1], E));
- res = min(res, bfs(S, D[2]) + bfs(D[2], D[1]) + bfs(D[1], D[0]) + bfs(D[0], E));
- }
- if(res >= 1000) {
- res = -1;
- }
- cout << res << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement