백준 7576 python [토마토]

인지용·2025년 1월 5일
0

알고리즘

목록 보기
16/46
post-thumbnail

https://www.acmicpc.net/status?user_id=qwef123&problem_id=7576&from_mine=1

코드

from collections import deque

# with open('./data.txt', 'r') as file:
#     lines = file.read().strip().split('\n')

# M, N = map(int, lines[0].split())
M, N = map(int, input().split())

box = []
for i in range(N):
    # box.append(list(map(int, lines[i+1].split())))
    box.append(list(map(int, input().split())))

moveX = [1, 0, -1, 0]
moveY = [0, -1, 0, 1]
Q = deque()

# 익은 토마토 먼저 전부 담기
for x in range(N):
    for y in range(M):
        if(box[x][y] == 1):
            Q.append((x, y))

while Q:
    nowX, nowY = Q.popleft()
    
    for i in range(4):
        nextX = nowX + moveX[i]
        nextY = nowY + moveY[i]
        
        if(nextX >= N or nextY >= M or nextX < 0 or nextY < 0):
            continue
        
        if(box[nextX][nextY] != 0):
            continue

        Q.append((nextX, nextY))
        box[nextX][nextY] = box[nowX][nowY] + 1


maxDay = max(map(max, box))
hasZero = any(0 in row for row in box)

if(maxDay == 1):
    print(0)
elif(hasZero):
    print(-1)
else:
    print(maxDay-1)

접근 방법

핵심은 이미 익은 토마토의 위치들을 먼저 다 확보하고
큐에 넣은 상태로 시작하는 것이다.

그리고 나머지 로직은 다른 문제들과 동일하게
while문을 돌면서 노드마다 이전 노드의 값 +1을 해주는 것이다. 노드 특성상 먼저 도착한게 제일 빨리 도착한 것이기 때문에 걸린 최소일 이라고 볼 수 있다.

아무튼 핵심을 몰라서 계속 결과가 6이 나오는 예제에서
6보다 더 많은 숫자가 나오면서 틀렸다.
그래서 혹시 먼저 다 찾아야되나? 하는 의문을 가지고
시도했다.

근데 계속 IndexError가 나는거다. 구조상 날 수가 없는데.. 뭐지 한참 고민하다 봤더니

아래에서 M, N이 아니라 N, M으로 오타가 났었다..
허허 이제 조심하자

# M, N = map(int, lines[0].split())
M, N = map(int, input().split())
profile
한-줄

0개의 댓글