[BOJ] 7576 토마토

[BOJ] 7576 토마토

문제 링크

나의 풀이

from collections import deque

#상하좌우
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

def bfs():
    queue = deque()
    count = 0
		# 익은 토마토 좌표를 count와 함께 큐 리스트에 append
    for v in xys:
        x = v[0]
        y = v[1]
        queue.append((x,y,count))

    while queue:
        a, b, cnt = queue.popleft()
        for i in range(4):
            nx = a + dx[i]
            ny = b + dy[i]
            if nx < 0 or nx >= m or ny < 0 or ny >= n:
                continue
            if tomatoes[nx][ny] == 0:
                tomatoes[nx][ny] = 1
                queue.append((nx,ny, cnt+1))

		# 덜 익은 토마토가 있으면 -1 반환
    for t in tomatoes:
        if 0 in t:
            return -1

		# 마지막에 도출된 cnt값을 반환
    return cnt


n, m = map(int, input().split())
tomatoes = [list(map(int, input().split())) for _ in range(m)]

xys = [] # 익은 토마토 좌표 리스트

# 익은 토마토 좌표 리스트 작성
for k in range(m):
    for l in range(n):
        if tomatoes[k][l] == 1:
            xys.append((k,l))


print(bfs())

© 2021. All rights reserved.