난이도 : GOLD V
문제링크 : https://www.acmicpc.net/problem/7569
문제해결 아이디어
- 평범한 BFS 문제.
- visited를 갱신할때 +1 더해가면서 날짜계산을 했다.
- 마지막에 안익은 토마토 있는지 확인하고 정답을 리턴.
소스코드
import sys
from collections import deque
import copy
def bfs():
while q:
x,y = q.popleft()
for k in range(4):
nx = x + dx[k]
ny = y + dy[k]
if 0 <= nx < n and 0 <= ny < m and not visited[nx][ny]:
q.append((nx, ny))
visited[nx][ny] = visited[x][y] + 1
input = sys.stdin.readline
m, n = map(int, input().split())
dx = [0,0,-1,1]
dy = [1,-1,0,0]
res = 0
graph = []
for _ in range(n):
graph.append(list(map(int, input().split())))
visited = copy.deepcopy(graph)
q = deque()
for i in range(n):
for j in range(m):
if graph[i][j] == 1:
q.append((i,j))
bfs()
for i in visited:
for j in i:
if j == 0:
print(-1)
exit(0)
res = max(res, max(i))
print(res - 1)