cgy12306
[백준 BoJ] 3055 - 탈출 본문
// https://www.acmicpc.net/problem/3055
// 탈출
#include<iostream>
#include<queue>
#include<string>
using namespace std;
int R, C;
char map[52][52];
int visited[52][52];
int dx[] = { 1,-1,0,0 };
int dy[] = { 0,0,1,-1 };
int goalx, goaly;
queue<pair<int, int>> w;
queue<pair<int, int>> q;
int bfs() {
visited[q.front().first][q.front().second] = 1;
while (!q.empty()) {
int wSize = w.size();
for (int i = 0; i < wSize; i++) {
int x = w.front().first;
int y = w.front().second;
w.pop();
for (int j = 0; j < 4; j++) {
int nx = x + dx[j];
int ny = y + dy[j];
if (nx < 0 || ny < 0 || nx >= R || ny >= C)continue;
if (map[nx][ny] == '.') {
map[nx][ny] = '*';
w.push({ nx,ny });
}
}
}
int qSize = q.size();
for (int i = 0; i < qSize; i++) {
int x = q.front().first;
int y = q.front().second;
q.pop();
if (x == goalx && y == goaly) return visited[x][y] - 1;
for (int j = 0; j < 4; j++) {
int nx = x + dx[j];
int ny = y + dy[j];
if (nx < 0 || ny < 0 || nx >= R || ny >= C)continue;
if (map[nx][ny] != '*' && map[nx][ny] != 'X' && visited[nx][ny] == 0) {
visited[nx][ny] = visited[x][y] + 1;
q.push({ nx,ny });
}
}
}
}
return -1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> R >> C;
for (int i = 0; i < R; i++) {
string s;
cin >> s;
for (int j = 0; j < s.size(); j++) {
map[i][j] = s[j];
if (s[j] == 'S') {
q.push({ i,j });
}
else if (s[j] == '*') {
w.push({ i,j });
}
else if (s[j] == 'D') {
goalx = i;
goaly = j;
}
}
}
int ans = bfs();
if (ans == -1) cout << "KAKTUS";
else cout << ans;
}
'Algorithm > C++' 카테고리의 다른 글
[백준 BoJ] 2636 - 치즈 (0) | 2022.03.19 |
---|---|
[백준 BoJ] 2206 - 벽 부수고 이동하기 (0) | 2022.03.18 |
[백준 BoJ] 24678 - 돌무더기 게임 1 (0) | 2022.03.13 |
[백준 BoJ] 1113 - 수영장 만들기 (0) | 2022.03.08 |
[백준 BoJ] 12582 - 1로 만들기 2 (0) | 2022.03.08 |
Comments