알고리즘/완전탐색(BFS,DFS)
BOJ - 5427 ) 불
개발자가될수있을까?
2020. 1. 17. 15:10

https://www.acmicpc.net/problem/5427
불의 번짐을 Queue에 넣고 맵을 업데이트하여
그 상황에서 상근이가 갈수있는 자리를 체크해준다.
상근이가 가장자리에 도착할 경우
Queue와 상관없이 종료한다.
|
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
#include <iostream>
#include <queue>
#define end '\n'
using namespace std;
int N, w, h;
int dx[] = { 0,0,+1,-1 };
int dy[] = { 1,-1,0,0 };
char map[1002][1002] = { {'0',}, };
bool visit[1002][1002] = { {false,}, };
typedef struct {
int y, x;
char pos;
int time;
}coordi;
int BFS(void) {
for (int index = 0; index < h; index++) {
for (int index_ = 0; index_ < w; index_++) {
map[index][index_] = '0';
visit[index][index_] = false;
}
}
cin >> w >> h;
for (int y = 0; y < h; y++) {
cin >> map[y];
}
queue < coordi > Q;
coordi start;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
if (map[y][x] == '@') {
start.y = y;
start.x = x;
if (y == h - 1 || y == 0 || x == w - 1 || x == 0) {
return 0;
}
}
else if (map[y][x] == '*') {
Q.push({ y ,x,'*',0 });
visit[y][x] = true;
}
}
}
Q.push(start);
while (!Q.empty()) {
char now_pos = Q.front().pos;
int now_x = Q.front().x;
int now_y = Q.front().y;
int time = Q.front().time;
Q.pop();
if (now_pos == '*') {
for (int index = 0; index < 4; index++) {
int nx = now_x + dx[index];
int ny = now_y + dy[index];
if (nx >= 0 && ny >= 0 && nx < w && ny < h) {
if (!visit[ny][nx]) {
if (map[ny][nx] != '#' && map[ny][nx] != '*') {
visit[ny][nx] = true;
map[ny][nx] = '*';
Q.push({ ny, nx, '*' , 0 });
}
}
}
}
}
else if (now_pos == '@') {
for (int index = 0; index < 4; index++) {
int nx = now_x + dx[index];
int ny = now_y + dy[index];
if (nx >= 0 && ny >= 0 && nx < w && ny < h) {
if (!visit[ny][nx]) {
if (map[ny][nx] == '.') {
if (nx == 0 || nx == w - 1 || ny == 0 || ny == h - 1) return time + 1;
visit[ny][nx] = true;
map[ny][nx] = '@';
Q.push({ ny, nx, '@',time + 1 });
}
}
}
}
}
}
return -1;
}
int main(void) {
cin >> N;
int a[102];
for (int index = 0; index < N; index++) {
a[index] = BFS();
}
for (int index = 0; index < N; index++) {
if (a[index]== -1) cout << "IMPOSSIBLE" << "\n";
else cout << a[index]+1 << "\n";
}
return 0;
}
|
cs |
