본문 바로가기

코딩 이야기/백준 풀이

백준 7576번: 토마토 파이썬 코드(bfs)

반응형

https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/600px-Python-logo-notext.svg.png

import sys
from collections import deque

x = [-1,1,0,0]
y = [0,0,-1,1]

count = 0

m,n = map(int, sys.stdin.readline().split())

box = [list(map(int,sys.stdin.readline().split()))for _ in range(n)]

def bfs():
    global count
    queue = deque([])
    for i in range(n):
        for j in range(m):
            if box[i][j] == 1:
                queue.append([i,j,0])
    while queue:
        a,b,c = queue.popleft()
        for k in range(4):
            aa = a + x[k]
            bb = b + y[k]
            if 0<=aa<n and 0<=bb<m:
                if box[aa][bb] == 0:
                    box[aa][bb] = 1
                    queue.append([aa,bb,c+1])
    count = c
    return

bfs()

for i in range(n):
    if 0 in box[i]:
        count = -1

print(count)
반응형