알고리즘
백준 3055번 탈출 C++
영춘권의달인
2022. 8. 10. 09:04
bfs문제인데, 고슴도치의 이동과 물의 이동을 따로 관리해주어야 한다. 그리고 고슴도치는 물이 찰 예정인 칸으로 이동할 수 없다고 했기 때문에 처음에 물이 먼저 이동을 해야한다. 그래서 물을 먼저 큐에 넣어주었다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int r, c;
int dRow[4] = { -1,0,1,0 };
int dCol[4] = { 0,1,0,-1 };
enum Type {
Hedgehog,
Water
};
struct Info {
int row;
int col;
int moveCnt;
Type type;
};
pair<int, int> start;
pair<int, int> target;
vector<vector<char>> board;
vector<vector<bool>> found;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> r >> c;
board = vector<vector<char>>(r, vector<char>(c));
found = vector<vector<bool>>(r, vector<bool>(c, false));
queue<Info> q;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cin >> board[i][j];
if (board[i][j] == 'S') start = { i,j };
if (board[i][j] == 'D') target = { i,j };
if (board[i][j] == '*') q.push({ i,j,0,Water });
}
}
q.push({ start.first,start.second,0,Hedgehog });
found[start.first][start.second] = true;
int ans = -1;
while (!q.empty()) {
auto curr = q.front();
q.pop();
if (curr.row == target.first && curr.col == target.second) {
ans = curr.moveCnt;
break;
}
for (int i = 0; i < 4; i++) {
int nextRow = curr.row + dRow[i];
int nextCol = curr.col + dCol[i];
if (nextRow < 0 || nextRow >= r) continue;
if (nextCol < 0 || nextCol >= c) continue;
if (board[nextRow][nextCol] == 'X') continue;
if (board[nextRow][nextCol] == '*') continue;
if (curr.type == Water) {
if (board[nextRow][nextCol] == 'D') continue;
board[nextRow][nextCol] = '*';
q.push({ nextRow,nextCol,curr.moveCnt + 1,Water });
}
else {
if (found[nextRow][nextCol]) continue;
found[nextRow][nextCol] = true;
q.push({ nextRow,nextCol,curr.moveCnt + 1,Hedgehog });
}
}
}
if (ans == -1) cout << "KAKTUS";
else cout << ans;
}