https://www.acmicpc.net/problem/7576
import sys
from collections import deque
input = sys.stdin.readline
m, n = map(int, input().split()) # 가로 m, 세로 n
arr = [list(map(int, input().split())) for _ in range(n)] # 입력 배열
# 방향 벡터 (상, 하, 좌, 우)
directions = [(1, 0), (-1, 0), (0, -1), (0, 1)]
def bfs():
q = deque()
# 익은 토마토 위치를 모두 큐에 추가
for i in range(n):
for j in range(m):
if arr[i][j] == 1:
q.append((i, j))
# BFS 탐색
while q:
x, y = q.popleft()
for dx, dy in directions:
nx, ny = x + dx, y + dy
# 범위 안에 있고, 익지 않은 토마토인 경우
if 0 <= nx < n and 0 <= ny < m and arr[nx][ny] == 0:
arr[nx][ny] = arr[x][y] + 1 # 날짜 갱신
q.append((nx, ny))
bfs() # BFS 수행
# 결과 계산
max_days = 0
for row in arr:
for cell in row:
if cell == 0: # 익지 않은 토마토가 있으면 -1 반환
print(-1)
sys.exit(0)
max_days = max(max_days, cell)
print(max_days - 1) # 초기값 1을 빼줌
이차원 배열 전체에서 최댓값 구하는 공식
max(map(max, arr))-1
'백준' 카테고리의 다른 글
백준 1987. 알파벳 (0) | 2025.01.21 |
---|---|
백준 1525. 퍼즐 (0) | 2025.01.21 |
프로그래머스 43164. 여행경로 (0) | 2025.01.20 |
백준 1600. 말이 되고픈 원숭이 (0) | 2025.01.20 |
백준 10814. 나이순 정렬 (0) | 2025.01.13 |