๐น ๋น์ฐ
1. ๋ฌธ์ ๋งํฌ
2. ์ฝ๋
Python3
35668KB
2724ms
PyPy3
218480KB
624ms
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
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
north_pole = []
iceberg = []
for _ in range(N):
north_pole.append(list(map(int, input().split())))
for i in range(N):
for j in range(M):
if north_pole[i][j] != 0:
iceberg.append((i, j))
from collections import deque
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
def bfs(x, y):
q = deque([])
q.append((x, y))
melt_ice = []
visited[x][y] = True
while q:
x, y = q.popleft()
minus = 0 # ๋ฐ๋ค ์ธ์ ์(๋
น๋ ์)
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < N and 0 <= ny < M:
# ์ด๋ ์์น๊ฐ ๋ฐ๋ค์ด๋ฉด ๋
น์
if north_pole[nx][ny] == 0:
minus += 1
# ์ด๋ ์์น๊ฐ ๋ฐฉ๋ฌธํ์ง ์์ ๋น์ฐ์ผ ๋
if visited[nx][ny] == False and north_pole[nx][ny] != 0:
visited[nx][ny] = True
q.append((nx, ny))
melt_ice.append((x, y, minus))
return melt_ice
year = -1
while True:
count = 0
year += 1
visited = [[False] * M for _ in range(N)]
melt = []
# 1๋
๋์ ์ค์ ๋น์ฐ ์ ์ฒดํฌ
for ic in iceberg:
i, j = ic
if visited[i][j] == False:
melt += bfs(i, j)
count += 1
if count > 1:
break
# ๋น์ฐ์ด ๋ค ๋
น์๋์ ์ชผ๊ฐ์ง์ง ์๋ ๊ฒฝ์ฐ
if count == 0:
year = 0
break
next_iceberg = []
# ๋น์ฐ์ ๋ณํ(๋
น์ ๋น์ฐ ๋ฐ์)
for m in melt:
i, j, num = m
north_pole[i][j] = max(0, north_pole[i][j] - num)
if north_pole[i][j] > 0:
next_iceberg.append((i, j))
iceberg = next_iceberg
print(year)
3. ํด์ค
์๊ฐ์ด๊ณผ๋ก ๊ณ ์ํ ๋ฌธ์ ..
bfs๋ฅผ ํตํด ์ฐ๊ฒฐ๋ ๋น์ฐ์ ์ฐพ๊ณ , ๋น์ฐ์ ๊ฐ์๋ฅผ ์ผ๋ค.
์๊ฐ์ด๊ณผ ๋ ๋ถ๋ถ์ ๋น์ฐ์ด ๋ น๋ ๊ฒ์ ๋ฐ์ํ ๋ ๋ฐ์ํ๊ณ , ํด๋น ๋ถ๋ถ์ ํด๊ฒฐํ๊ธฐ ์ํด bfs๋ฅผ ์คํํ ๋ ๋น์ฐ์ ์์น์ ๋ น๋ ์์ ๋ฐ์ ์ฒ๋ฆฌํด์ฃผ์๋ค.
This post is licensed under CC BY 4.0 by the author.