-문제링크
7576번: 토마토
첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토
www.acmicpc.net
-풀이
from collections import deque
dx = [-1, 1, 0, 0]
dy = [0, 0, 1, -1]
m, n = map(int, input().split())
maps = [list(map(int,input().split())) for _ in range(n)]
q = deque()
for i in range(n):
for j in range(m):
if maps[i][j] == 1:
q.append([i,j])
while q:
x, y = q.popleft()
for i in range(4):
nx = x+dx[i]
ny = y+dy[i]
if 0<= nx <n and 0<= ny <m and maps[nx][ny] == 0:
maps[nx][ny] = maps[x][y] + 1
q.append([nx,ny])
for i in range(n):
if 0 in maps[i] :
print(-1)
break
else :
print(max(max(maps))-1)
'알고리즘' 카테고리의 다른 글
[백준] 2667. 단지번호붙이기 (DFS/Python) (0) | 2020.10.21 |
---|---|
[SWEA] 5097. 회전 (Python) (0) | 2020.10.21 |
[백준] 2589. 보물섬 (Python) (0) | 2020.10.21 |
[백준] 1260. DFS와 BFS (Python) (0) | 2020.10.21 |
[SWEA] 1953. 탈주범 검거 (Python) (0) | 2020.10.21 |