Post

[BOJ] 7576. ํ† ๋งˆํ† (python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

  1. ์•ˆ์ต์€ ํ† ๋งˆํ† ์˜ ๊ฐฏ์ˆ˜ ์„ธ๊ธฐ
    ์•ˆ์ต์€ ํ† ๋งˆํ† ๊ฐ€ 0๊ฐœ๋ฉด 0์ถœ๋ ฅ ํ›„ ํ”„๋กœ๊ทธ๋žจ์ข…๋ฃŒ

  2. ์ต์€ ํ† ๋งˆํ†  ์œ„์น˜
    ๋™์‹œ์— ํ† ๋งˆํ† ๋“ค์ด ์ต๊ธฐ ์‹œ์ž‘ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ด๋ฏธ ์ต์€ ํ† ๋งˆํ† ๋“ค์˜ ์œ„์น˜๋ฅผ ์ฐพ์•„์„œ ์‹œ๊ฐ„์„ ์„ธํŒ…ํ•ด์•ผํ•œ๋‹ค.

  3. ๋ชจ๋“  ํ† ๋งˆํ† ๊ฐ€ ์ต์„ ๋•Œ๊นŒ์ง€ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„ ์„ธ๊ธฐ
    ์ต์€ ํ† ๋งˆํ† ๋ฉด ์ƒํ•˜์ขŒ์šฐ๊ฒ€์‚ฌํ•ด์„œ

    • ์•ˆ์ต์€ ํ† ๋งˆํ†  ์ต์€ ํ† ๋งˆํ† ๋กœ ์ƒํƒœ๋ฐ”๊พธ๊ธฐ
    • ์•ˆ์ต์€ ํ† ๋งˆํ†  ๊ฐœ์ˆ˜ -1
    • day+=1
    • queue๋„ฃ๊ธฐ

bfs๋ฅผ ๋น ์ ธ๋‚˜์˜จ ์ƒํƒœ์—์„œ ๋” ์ต์„ ํ† ๋งˆํ† ๊ฐ€ ์žˆ์œผ๋ฉด -1์ถœ๋ ฅํ•˜๊ธฐ

๐Ÿฅ‚์ฝ”๋“œ

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
import sys
from collections import deque
input = sys.stdin.readline

m,n = map(int,input().split())
ground=[]
unripe = 0
for _ in range(n):
    ground.append(list(map(int,input().split())))
    unripe += ground[-1].count(0)

if unripe == 0 : print(0)
else:
    dy = (-1,0,1,0)
    dx = (0,1,0,-1)
    queue = deque()

    for y in range(n):
        for x in range(m):
            if ground[y][x]==1:
                queue.append((0,y,x))

    while queue:
        day,ny,nx = queue.popleft()
        for i in range(4):
            ey,ex = ny+dy[i], nx+dx[i]
            if 0<=ey<n and 0<=ex<m:
                if ground[ey][ex]==0:
                    unripe -=1
                    if unripe == 0:
                        print(day+1)
                        exit(0)
                    ground[ey][ex]=1
                    queue.append((day+1,ey,ex))
    print(-1)
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.