반응형
문제 링크: https://www.acmicpc.net/problem/5427
5427번: 불
상근이는 빈 공간과 벽으로 이루어진 건물에 갇혀있다. 건물의 일부에는 불이 났고, 상근이는 출구를 향해 뛰고 있다. 매 초마다, 불은 동서남북 방향으로 인접한 빈 공간으로 퍼져나간다. 벽에
www.acmicpc.net
<문제 풀이> BFS
이 문제는 4179번 문제에서 테스트 케이스가 추가된 문제입니다.
각 테스트 케이스마다 배열을 초기화하는 작업만 추가하면 됩니다.
https://seokjin2.tistory.com/67
[백준 4179번] 불!
문제 링크:https://www.acmicpc.net/problem/4179 4179번: 불! 입력의 첫째 줄에는 공백으로 구분된 두 정수 R과 C가 주어진다. 단, 1 ≤ R, C ≤ 1000 이다. R은 미로 행의 개수, C는 열의 개수이다. 다음 입력으..
seokjin2.tistory.com
<C++ 소스 코드>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
#include <iostream>
#include <string>
#include <algorithm>
#include <queue>
#include <vector>
#include <stack>
#include <utility>
#include <climits>
using namespace std;
#define X first
#define Y second
int dx[4] = { 0, 1, 0, -1 };
int dy[4] = { 1 , 0, -1, 0 };
char board[1000][1000];
int fire[1000][1000];
int person[1000][1000];
int w, h;
void f_bfs() {
queue<pair<int, int> >Q;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (board[i][j] == '*') {
Q.push({ i, j });
fire[i][j] = 1;
}
}
}
while (!Q.empty()) {
auto cur = Q.front(); Q.pop();
for (int dir = 0; dir < 4; dir++) {
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if (nx < 0 || ny < 0 || nx >= h || ny >= w)continue;
if (board[nx][ny] == '#' || fire[nx][ny])continue;
fire[nx][ny] = fire[cur.X][cur.Y] + 1;
Q.push({ nx, ny });
}
}
}
int p_bfs() {
f_bfs();
queue<pair<int, int> >Q;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (board[i][j] == '@') {
Q.push({ i, j });
person[i][j] = 1;
}
}
}
while (!Q.empty()) {
auto cur = Q.front(); Q.pop();
for (int dir = 0; dir < 4; dir++) {
int nx = cur.X + dx[dir];
int ny = cur.Y + dy[dir];
if (nx < 0 || ny < 0 || nx >= h || ny >= w) { // 탈출 성공
return person[cur.X][cur.Y];
}
if (board[nx][ny] == '#' || (person[cur.X][cur.Y] + 1 >= fire[nx][ny] && fire[nx][ny]) || person[nx][ny])continue; //벽 또는 불 때문에 이동 못하는 경우
person[nx][ny] = person[cur.X][cur.Y] + 1;
Q.push({ nx, ny });
}
}
return 0; // 탈출 실패
}
int main(void) {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int test_case; cin >> test_case;
while (test_case--) {
cin >> w >> h;
for (int i = 0; i < h; i++) {
string s; cin >> s;
for (int j = 0; j < w; j++) {
board[i][j] = s[j];
}
}
int res = p_bfs();
if (res) cout << res << '\n';
else cout << "IMPOSSIBLE\n";
fill(&fire[0][0], &fire[999][1000], 0);
fill(&person[0][0], &person[999][1000], 0);
}
return 0;
}
|
cs |
반응형
'알고리즘 문제풀이 > 백준' 카테고리의 다른 글
[백준 5014번] 스타트링크 (0) | 2021.11.19 |
---|---|
[백준 2146번] 다리 만들기 (0) | 2021.11.19 |
[백준 7562번] 나이트의 이동 (0) | 2021.11.16 |
[백준 10026번] 적록색약 (0) | 2021.11.05 |
[백준 4179번] 불! (0) | 2021.11.04 |