[Python] 백준 7576: 토마토
https://www.acmicpc.net/problem/7576
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토
www.acmicpc.net
ANS
import sys
input = sys.stdin.readline
from collections import deque
q = deque()
dir = [(0, -1), (0, 1), (1, 0), (-1, 0)]
def bfs():
while q:
x, y = q.popleft()
for k in range(4):
nx = x + dir[k][0]
ny = y + dir[k][1]
if 0 <= nx < N and 0 <= ny < M and arr[nx][ny] == 0:
arr[nx][ny] = arr[x][y] +1
q.append((nx, ny))
M, N = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(N)]
for r in range(N):
for c in range(M):
if arr[r][c] == 1:
q.append((r,c))
res = 0
bfs()
#sumV 합을 구한다.
for i in arr:
for k in i:
if k == 0:
print(-1)
exit(0)
res = max(res, max(i))
print(res-1)
BFS 문제. 한 번에 여러 부분에서 BFS를 도는 것을 잘 설계해주어야 한다.
'알고리즘 > 백준' 카테고리의 다른 글
| [Python] SWEA 5188: 최소합, 5189: 전자카트 (0) | 2023.03.27 |
|---|---|
| [Python] 백준 14501: 퇴사 (0) | 2023.03.22 |
| [Python] 백준 15686: 치킨집 (0) | 2023.03.15 |
| [Python] 백준 7562: 나이트의 이동 (0) | 2023.03.14 |
| [Python] 백준 4963: 섬의 개수 (0) | 2023.03.12 |
TAGS.
