Post

๐Ÿน ๋น™์‚ฐ

1. ๋ฌธ์ œ ๋งํฌ

2573๋ฒˆ: ๋น™์‚ฐ


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.