코테 준비/DFS, BFS
[백준] 7576. 토마토 (DFS)
imsmile2000
2023. 1. 31. 03:13
from collections import deque
dx=[-1,1,0,0]
dy=[0,0,-1,1]
def dfs(graph):
queue=deque()
for i in range(n):
for j in range(m):
if graph[i][j]==1: #그래프를 모두 탐색하여 1인 좌표들을 모두 queue에 넣는다
queue.append((i,j))
while queue:
x,y=queue.popleft()
for i in range(4):
nx=x+dx[i]
ny=y+dy[i]
if nx<0 or ny<0 or nx>=n or ny>=m:
continue
if graph[nx][ny]==0: #주변 좌표가 0이면
graph[nx][ny]=graph[x][y]+1 #이전 좌표에+1
queue.append((nx,ny))
m,n=map(int,input().split())
graph=[[0]*m for _ in range(n)]
count=0
count2=0
M=0
for i in range(n):
graph[i]=list(map(int,input().split()))
count+=graph[i].count(0)
if count==0: # graph에 0이 한개도 없을 때 즉, 모두 익은 상태면
print(0) # 0 출력
else: #애초에 모두 익은 상태가 아니라면
dfs(graph) #dfs실행
for j in range(n):
count2+=graph[j].count(0)
M=max(M,max(graph[j])) #graph에서 가장 큰 숫자 찾기
if count2!=0: # dfs를 실행했는데도 안익은 토마토가 남아있다면
print(-1) # -1출력
else:
print(M-1) #가장큰 숫자-1 출력