ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

7576๋ฒˆ: ํ† ๋งˆํ† 

์ฒซ ์ค„์—๋Š” ์ƒ์ž์˜ ํฌ๊ธฐ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋‘ ์ •์ˆ˜ M,N์ด ์ฃผ์–ด์ง„๋‹ค. M์€ ์ƒ์ž์˜ ๊ฐ€๋กœ ์นธ์˜ ์ˆ˜, N์€ ์ƒ์ž์˜ ์„ธ๋กœ ์นธ์˜ ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค. ๋‹จ, 2 ≤ M,N ≤ 1,000 ์ด๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ๋Š” ํ•˜๋‚˜์˜ ์ƒ์ž์— ์ €์žฅ๋œ ํ† ๋งˆํ† ๏ฟฝ

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ์ต์€ ํ† ๋งˆํ† ์™€ ์•ˆ ์ต์€ ํ† ๋งˆํ† ๊ฐ€ ์ธ์ ‘ํ•ด์žˆ๋‹ค๋ฉด ์ƒ, ํ•˜, ์ขŒ, ์šฐ๋กœ ํ•œ ์นธ์”ฉ ์˜ํ–ฅ์„ ๋ฐ›์•„ ํ† ๋งˆํ† ๊ฐ€ ์ต๊ฒŒ ๋œ๋‹ค. ์ƒ์ž์— ํ† ๋งˆํ† ๋“ค์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ๋ชจ๋“  ํ† ๋งˆํ† ๊ฐ€ ์ต๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ๋‚ ์งœ๋ฅผ ๊ณ„์‚ฐํ•˜์—ฌ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋œ๋‹ค.

 

 ์œ„์˜ ๊ทธ๋ฆผ์€ ์˜ˆ์ œ ์ž…๋ ฅ 1์ด๋‹ค. ์˜ˆ์ œ ์ž…๋ ฅ 1์˜ ๊ฒฝ์šฐ ํ† ๋งˆํ† ๊ฐ€ ์ต๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„์€ 8์ผ์ด ์†Œ์š”๋œ๋‹ค. ์ด๋Š” ์šฐ์ธก ํ•˜๋‹จ์— ์žˆ๋Š” ์ต์€ ํ† ๋งˆํ† ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด ํ•˜๋ฃจ๊ฐ€ ์ง€๋‚จ์— ๋”ฐ๋ผ ๋Œ€๊ฐ์„  ๋ฐฉํ–ฅ์œผ๋กœ ํ† ๋งˆํ† ๋“ค์ด ์ต๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋”ฐ๋ผ์„œ ๋‹จ์ˆœํžˆ ์ƒ, ํ•˜, ์ขŒ, ์šฐ๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ ๋™์ผํ•œ ๋‚ ์— ์˜ํ–ฅ์„ ๋ฐ›์€ ๊ฒƒ์ธ์ง€ ํŒ๋‹จํ•˜๋Š” ๊ณผ์ •์ด ํ•„์š”ํ•˜๋‹ค.

 

์ฝ”๋“œ

from sys import stdin
from collections import deque


def visitable(x, y):
    return 0 <= x < n and 0 <= y < m and not graph[x][y]


def bfs():
    cnt = -1

    while q:
        cnt += 1

        for _ in range(len(q)):
            cur_x, cur_y = q.popleft()

            for x, y in dirs:
                next_x, next_y = x + cur_x, y + cur_y
                if visitable(next_x, next_y):
                    graph[next_x][next_y] = 1
                    q.append([next_x, next_y])

    unripe = [True for tomatoes in graph if 0 in tomatoes]

    return -1 if unripe else cnt


if __name__ == "__main__":
    m, n = map(int, stdin.readline().split())
    graph = [list(map(int, stdin.readline().split())) for _ in range(n)]
    dirs = ((0, 1), (0, -1), (1, 0), (-1, 0))
    q = deque()
    for i in range(n):
        for j in range(m):
            if graph[i][j] == 1:
                q.append([i, j])

    print(bfs())

 ์ด๋ฅผ ์ฝ”๋“œ๋กœ ๊ตฌํ˜„ํ•œ๋‹ค๋ฉด, ํ˜„์žฌ ํ์— ์žˆ๋Š” ํ† ๋งˆํ† ๋“ค์„ ๋ชจ๋‘ ์ฒ˜๋ฆฌํ•˜์—ฌ์•ผ ํ•˜๋ฃจ์— ์ต์„ ์ˆ˜ ์žˆ๋Š” ํ† ๋งˆํ† ๋“ค์ด ์ฒ˜๋ฆฌ๋œ ๊ฒƒ์ด๋‹ค. ๋”ฐ๋ผ์„œ ๋‹ค๋ฅธ ๊ทธ๋ž˜ํ”„ ๋ฌธ์ œ ๋“ค๊ณผ ๋‹ฌ๋ฆฌ, 2์ค‘ ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด ์ฒ˜๋ฆฌํ•ด์ฃผ์–ด์•ผํ•œ๋‹ค๋Š” ์ ์ด ๋‹ค๋ฅด๋‹ค.

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€