File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ # https://www.acmicpc.net/problem/7576
2+
3+ import sys
4+ input = sys .stdin .readline
5+ from collections import deque
6+
7+ def bfs ():
8+ M , N = map (int , input ().split ()) # N이 행, M이 열
9+ graph = [list (map (int , input ().split ())) for _ in range (N )]
10+
11+ dx = [- 1 , 1 , 0 , 0 ]
12+ dy = [0 , 0 , - 1 , 1 ]
13+
14+ # multi source dfs
15+ q = deque ()
16+ for i in range (N ):
17+ for j in range (M ):
18+ if graph [i ][j ] == 1 : # 토마토가 익은 게 있으면 무조건 q에 넣기
19+ q .append ((i , j ))
20+
21+ while q :
22+ x , y = q .popleft ()
23+
24+ for i in range (4 ):
25+ nx = x + dx [i ]
26+ ny = y + dy [i ]
27+
28+ if 0 <= nx < N and 0 <= ny < M and graph [nx ][ny ] == 0 : # 안 익었으면
29+ graph [nx ][ny ] = graph [x ][y ] + 1 # graph[x][y]보다 하루씩 더 걸림
30+ q .append ((nx , ny )) # q에 또 넣어주기
31+
32+ # 출력
33+ max_value = 0
34+ for i in range (N ):
35+ for j in range (M ):
36+ if graph [i ][j ] == 0 : # 안 익은 게 있으면 -1 로 print
37+ print (- 1 )
38+ return
39+ max_value = max (max_value , graph [i ][j ])
40+
41+ print (max_value - 1 ) # 처음에 익은 토마토가 1로 들어오기 때문에 1일치 빼서 -1 해줘야 함
42+ # 처음부터 다 익어있는 경우: -1 또는 1뿐!!! max_value = 1일 거고, 1 - 1 = 0 이므로 print(0) 됨.
43+
44+ bfs ()
You can’t perform that action at this time.
0 commit comments