https://www.acmicpc.net/problem/7576
이제 토마토는 마스터했다고 생각했는데 아니었다 ㅎ
모든 위치에 토마토가 있는 경우를 고려 안 해서 틀렸지만 그 부분만 고치니 바로 풀렸다.
놓치는 예외상황이 너무 많아서 걱정이다..
import sys
from collections import deque
input = sys.stdin.readline
m, n = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(n)]
tomatos = deque()
for i in range(n):
for j in range(m):
if board[i][j] == 1:
tomatos.append((i, j))
di = [0, 1, 0, -1]
dj = [1, 0, -1, 0]
visited = [[False for _ in range(m)] for _ in range(n)]
while tomatos:
ti, tj = tomatos.popleft()
visited[ti][tj] = True
for d in range(4):
ni, nj = ti + di[d] , tj + dj[d]
if 0 <= ni < n and 0 <= nj < m and not visited[ni][nj]:
if board[ni][nj] != -1 and board[ni][nj] == 0:
board[ni][nj] = board[ti][tj] + 1
visited[ni][nj] = True
tomatos.append((ni, nj))
day = 0
flag = False
for i in range(n):
for j in range(m):
if board[i][j] == 0:
flag = True
day = max(day, board[i][j])
if flag:
print(-1)
else:
print(day - 1)
'PS > 백준' 카테고리의 다른 글
[백준] 17837번 새로운 게임 2 (python) (0) | 2025.02.12 |
---|---|
[백준] 2146번 다리 만들기 (python) (0) | 2025.01.09 |
[백준] 1600번 말이 되고픈 원숭이 (python) (0) | 2024.12.30 |
[백준] 2667번 단지번호붙이기 (python/정답코드) (0) | 2024.12.22 |
[백준] 1913번 달팽이 (python 정답 코드) (0) | 2024.10.10 |