Skip to content

Commit 7dda0ec

Browse files
committed
[Update] bfs예제 풀이
1 parent 8e425c9 commit 7dda0ec

File tree

1 file changed

+126
-0
lines changed

1 file changed

+126
-0
lines changed
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
#include <iostream>
2+
#include <queue>
3+
#include <string>
4+
5+
#define MAX 51
6+
#define MAX_VAL 2501
7+
8+
using namespace std;
9+
10+
int r, c;
11+
int d, s;
12+
13+
string map[MAX];
14+
int dp[MAX][MAX];
15+
16+
queue<pair<int, int>> q;
17+
queue<pair<int, int>> waterQueue;
18+
19+
void init() {
20+
for (int i = 0; i < r; i++) {
21+
for (int j = 0; j < c; j++) {
22+
dp[i][j] = MAX_VAL;
23+
}
24+
}
25+
}
26+
27+
bool inRange(int x, int y) {
28+
return (0 <= x && x < r && 0 <= y && y < c);
29+
}
30+
31+
void findMinPath() {
32+
int dx[] = { -1, 1, 0, 0 };
33+
int dy[] = { 0, 0, -1, 1 };
34+
35+
while (!q.empty()) {
36+
//현재 물이 범람한 칸만 탐색하기 위함이다.
37+
int waterQueueSize = waterQueue.size();
38+
for (int i = 0; i < waterQueueSize; i++) {
39+
40+
int currentWaterX = waterQueue.front().first;
41+
int currentWaterY = waterQueue.front().second;
42+
waterQueue.pop();
43+
44+
for (int j = 0; j < 4; j++) {
45+
int nextWaterX = currentWaterX + dx[j];
46+
int nextWaterY = currentWaterY + dy[j];
47+
48+
//범위 밖인지 확인한다.
49+
if (!inRange(nextWaterX, nextWaterY))
50+
continue;
51+
52+
if (map[nextWaterX][nextWaterY] == '.') {
53+
//해당 칸은 물이 범람함
54+
map[nextWaterX][nextWaterY] = '*';
55+
waterQueue.push({ nextWaterX, nextWaterY });
56+
}
57+
}
58+
}
59+
int queueSize = q.size();
60+
61+
for (int i = 0; i < queueSize; i++) {
62+
int x = q.front().first;
63+
int y = q.front().second;
64+
int dis = dp[x][y];
65+
q.pop();
66+
67+
//도착지점이면 종료한다 (어차피 BFS)
68+
if (map[x][y] == 'D') {
69+
cout << dp[x][y];
70+
return;
71+
}
72+
73+
for (int j = 0; j < 4; j++) {
74+
int nx = x + dx[j];
75+
int ny = y + dy[j];
76+
int nextDis = dis + 1;
77+
78+
if (!inRange(nx, ny) || (nextDis >= dp[nx][ny]))
79+
continue;
80+
//물이 범람한 지역이거나 출발 지점인 경우는 건너띈다. (돌 포함)
81+
if (map[nx][ny] == '*' || map[nx][ny] == 'S' || map[nx][ny] == 'X')
82+
continue;
83+
84+
//최단 시간 갱신하고, queue에 넣는다.
85+
dp[nx][ny] = nextDis;
86+
q.push({ nx, ny });
87+
}
88+
}
89+
}
90+
91+
//결국 목적지에 도달하지 못한 경우에 해당한다.
92+
cout << "KAKTUS";
93+
return;
94+
}
95+
96+
int main() {
97+
ios::sync_with_stdio(false);
98+
cin.tie(NULL);
99+
cout.tie(NULL);
100+
101+
int desX, desY;
102+
103+
cin >> r >> c;
104+
105+
init();
106+
107+
for (int i = 0; i < r; i++) {
108+
string row;
109+
cin >> row;
110+
map[i] = row;
111+
112+
for (int j = 0; j < c; j++) {
113+
if (row[j] == '*') {
114+
waterQueue.push({ i, j });
115+
}
116+
else if (row[j] == 'S') {
117+
q.push({ i, j });
118+
dp[i][j] = 0;
119+
}
120+
}
121+
}
122+
123+
findMinPath();
124+
125+
return 0;
126+
}

0 commit comments

Comments
 (0)